blob: c80e60278b45f4ef1163b416b4f030d63db41e7a [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
Alexey Bataev2377fe92015-09-10 08:12:02 +000023void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000024 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000025 const RecordDecl *RD = S.getCapturedRecordDecl();
26 auto CurField = RD->field_begin();
27 auto CurCap = S.captures().begin();
28 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
29 E = S.capture_init_end();
30 I != E; ++I, ++CurField, ++CurCap) {
31 if (CurField->hasCapturedVLAType()) {
32 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000033 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000034 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000035 } else if (CurCap->capturesThis())
36 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000037 else if (CurCap->capturesVariableByCopy())
38 CapturedVars.push_back(
39 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
40 else {
41 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000042 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000043 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000044 }
45}
46
Samuel Antao4af1b7b2015-12-02 17:44:43 +000047static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
48 StringRef Name, LValue AddrLV,
49 bool isReferenceType = false) {
50 ASTContext &Ctx = CGF.getContext();
51
52 auto *CastedPtr = CGF.EmitScalarConversion(
53 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
54 Ctx.getPointerType(DstType), SourceLocation());
55 auto TmpAddr =
56 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
57 .getAddress();
58
59 // If we are dealing with references we need to return the address of the
60 // reference instead of the reference of the value.
61 if (isReferenceType) {
62 QualType RefType = Ctx.getLValueReferenceType(DstType);
63 auto *RefVal = TmpAddr.getPointer();
64 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
65 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
66 CGF.EmitScalarInit(RefVal, TmpLVal);
67 }
68
69 return TmpAddr;
70}
71
Alexey Bataev2377fe92015-09-10 08:12:02 +000072llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +000073CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000074 assert(
75 CapturedStmtInfo &&
76 "CapturedStmtInfo should be set when generating the captured function");
77 const CapturedDecl *CD = S.getCapturedDecl();
78 const RecordDecl *RD = S.getCapturedRecordDecl();
79 assert(CD->hasBody() && "missing CapturedDecl body");
80
81 // Build the argument list.
82 ASTContext &Ctx = CGM.getContext();
83 FunctionArgList Args;
84 Args.append(CD->param_begin(),
85 std::next(CD->param_begin(), CD->getContextParamPosition()));
86 auto I = S.captures().begin();
87 for (auto *FD : RD->fields()) {
88 QualType ArgType = FD->getType();
89 IdentifierInfo *II = nullptr;
90 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +000091
92 // If this is a capture by copy and the type is not a pointer, the outlined
93 // function argument type should be uintptr and the value properly casted to
94 // uintptr. This is necessary given that the runtime library is only able to
95 // deal with pointers. We can pass in the same way the VLA type sizes to the
96 // outlined function.
97 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
98 I->capturesVariableArrayType())
99 ArgType = Ctx.getUIntPtrType();
100
101 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000102 CapVar = I->getCapturedVar();
103 II = CapVar->getIdentifier();
104 } else if (I->capturesThis())
105 II = &getContext().Idents.get("this");
106 else {
107 assert(I->capturesVariableArrayType());
108 II = &getContext().Idents.get("vla");
109 }
110 if (ArgType->isVariablyModifiedType())
111 ArgType = getContext().getVariableArrayDecayedType(ArgType);
112 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
113 FD->getLocation(), II, ArgType));
114 ++I;
115 }
116 Args.append(
117 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
118 CD->param_end());
119
120 // Create the function declaration.
121 FunctionType::ExtInfo ExtInfo;
122 const CGFunctionInfo &FuncInfo =
123 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
124 /*IsVariadic=*/false);
125 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
126
127 llvm::Function *F = llvm::Function::Create(
128 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
129 CapturedStmtInfo->getHelperName(), &CGM.getModule());
130 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
131 if (CD->isNothrow())
132 F->addFnAttr(llvm::Attribute::NoUnwind);
133
134 // Generate the function.
135 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
136 CD->getBody()->getLocStart());
137 unsigned Cnt = CD->getContextParamPosition();
138 I = S.captures().begin();
139 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000140 // If we are capturing a pointer by copy we don't need to do anything, just
141 // use the value that we get from the arguments.
142 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
143 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
144 ++Cnt, ++I;
145 continue;
146 }
147
Alexey Bataev2377fe92015-09-10 08:12:02 +0000148 LValue ArgLVal =
149 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
150 AlignmentSource::Decl);
151 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000152 LValue CastedArgLVal =
153 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
154 Args[Cnt]->getName(), ArgLVal),
155 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000156 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000157 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000158 auto VAT = FD->getCapturedVLAType();
159 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
160 } else if (I->capturesVariable()) {
161 auto *Var = I->getCapturedVar();
162 QualType VarTy = Var->getType();
163 Address ArgAddr = ArgLVal.getAddress();
164 if (!VarTy->isReferenceType()) {
165 ArgAddr = EmitLoadOfReference(
166 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
167 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000168 setAddrOfLocalVar(
169 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000170 } else if (I->capturesVariableByCopy()) {
171 assert(!FD->getType()->isAnyPointerType() &&
172 "Not expecting a captured pointer.");
173 auto *Var = I->getCapturedVar();
174 QualType VarTy = Var->getType();
175 setAddrOfLocalVar(I->getCapturedVar(),
176 castValueFromUintptr(*this, FD->getType(),
177 Args[Cnt]->getName(), ArgLVal,
178 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000179 } else {
180 // If 'this' is captured, load it into CXXThisValue.
181 assert(I->capturesThis());
182 CXXThisValue =
183 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
184 }
185 ++Cnt, ++I;
186 }
187
Serge Pavlov3a561452015-12-06 14:32:39 +0000188 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000189 CapturedStmtInfo->EmitBody(*this, CD->getBody());
190 FinishFunction(CD->getBodyRBrace());
191
192 return F;
193}
194
Alexey Bataev9959db52014-05-06 10:08:46 +0000195//===----------------------------------------------------------------------===//
196// OpenMP Directive Emission
197//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000198void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000199 Address DestAddr, Address SrcAddr, QualType OriginalType,
200 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000201 // Perform element-by-element initialization.
202 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000203
204 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000205 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000206 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
207 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
208
209 auto SrcBegin = SrcAddr.getPointer();
210 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000211 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000212 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
213 // The basic structure here is a while-do loop.
214 auto BodyBB = createBasicBlock("omp.arraycpy.body");
215 auto DoneBB = createBasicBlock("omp.arraycpy.done");
216 auto IsEmpty =
217 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
218 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000219
Alexey Bataev420d45b2015-04-14 05:11:24 +0000220 // Enter the loop body, making that address the current address.
221 auto EntryBB = Builder.GetInsertBlock();
222 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000223
224 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
225
226 llvm::PHINode *SrcElementPHI =
227 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
228 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
229 Address SrcElementCurrent =
230 Address(SrcElementPHI,
231 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
232
233 llvm::PHINode *DestElementPHI =
234 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
235 DestElementPHI->addIncoming(DestBegin, EntryBB);
236 Address DestElementCurrent =
237 Address(DestElementPHI,
238 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000239
Alexey Bataev420d45b2015-04-14 05:11:24 +0000240 // Emit copy.
241 CopyGen(DestElementCurrent, SrcElementCurrent);
242
243 // Shift the address forward by one element.
244 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000245 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000246 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000247 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000248 // Check whether we've reached the end.
249 auto Done =
250 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
251 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000252 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
253 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000254
255 // Done.
256 EmitBlock(DoneBB, /*IsFinished=*/true);
257}
258
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000259/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000260/// \param DestAddr Address of the array.
261/// \param Type Type of array.
262/// \param Init Initial expression of array.
263static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
264 QualType Type, const Expr *Init) {
265 // Perform element-by-element initialization.
266 QualType ElementTy;
267
268 // Drill down to the base element type on both arrays.
269 auto ArrayTy = Type->getAsArrayTypeUnsafe();
270 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
271 DestAddr =
272 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
273
274 auto DestBegin = DestAddr.getPointer();
275 // Cast from pointer to array type to pointer to single element.
276 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
277 // The basic structure here is a while-do loop.
278 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
279 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
280 auto IsEmpty =
281 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
282 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
283
284 // Enter the loop body, making that address the current address.
285 auto EntryBB = CGF.Builder.GetInsertBlock();
286 CGF.EmitBlock(BodyBB);
287
288 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
289
290 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
291 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
292 DestElementPHI->addIncoming(DestBegin, EntryBB);
293 Address DestElementCurrent =
294 Address(DestElementPHI,
295 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
296
297 // Emit copy.
298 {
299 CodeGenFunction::RunCleanupsScope InitScope(CGF);
300 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
301 /*IsInitializer=*/false);
302 }
303
304 // Shift the address forward by one element.
305 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
306 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
307 // Check whether we've reached the end.
308 auto Done =
309 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
310 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
311 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
312
313 // Done.
314 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
315}
316
John McCall7f416cc2015-09-08 08:05:57 +0000317void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
318 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000319 const VarDecl *SrcVD, const Expr *Copy) {
320 if (OriginalType->isArrayType()) {
321 auto *BO = dyn_cast<BinaryOperator>(Copy);
322 if (BO && BO->getOpcode() == BO_Assign) {
323 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000324 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000325 } else {
326 // For arrays with complex element types perform element by element
327 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000328 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000329 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000330 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000331 // Working with the single array element, so have to remap
332 // destination and source variables to corresponding array
333 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000334 CodeGenFunction::OMPPrivateScope Remap(*this);
335 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000336 return DestElement;
337 });
338 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000339 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000340 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000341 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000342 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000343 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000344 } else {
345 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000346 CodeGenFunction::OMPPrivateScope Remap(*this);
347 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
348 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000349 (void)Remap.Privatize();
350 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000351 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000352 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000353}
354
Alexey Bataev69c62a92015-04-15 04:52:20 +0000355bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
356 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000357 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000358 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000359 auto IRef = C->varlist_begin();
360 auto InitsRef = C->inits().begin();
361 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000362 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000363 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
364 EmittedAsFirstprivate.insert(OrigVD);
365 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
366 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
367 bool IsRegistered;
368 DeclRefExpr DRE(
369 const_cast<VarDecl *>(OrigVD),
370 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
371 OrigVD) != nullptr,
372 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000373 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000374 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000375 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000376 // Emit VarDecl with copy init for arrays.
377 // Get the address of the original variable captured in current
378 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000379 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000380 auto Emission = EmitAutoVarAlloca(*VD);
381 auto *Init = VD->getInit();
382 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
383 // Perform simple memcpy.
384 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000385 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000386 } else {
387 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000388 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000389 [this, VDInit, Init](Address DestElement,
390 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000391 // Clean up any temporaries needed by the initialization.
392 RunCleanupsScope InitScope(*this);
393 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000394 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000395 EmitAnyExprToMem(Init, DestElement,
396 Init->getType().getQualifiers(),
397 /*IsInitializer*/ false);
398 LocalDeclMap.erase(VDInit);
399 });
400 }
401 EmitAutoVarCleanups(Emission);
402 return Emission.getAllocatedAddress();
403 });
404 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000405 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000406 // Emit private VarDecl with copy init.
407 // Remap temp VDInit variable to the address of the original
408 // variable
409 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000410 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000411 EmitDecl(*VD);
412 LocalDeclMap.erase(VDInit);
413 return GetAddrOfLocalVar(VD);
414 });
415 }
416 assert(IsRegistered &&
417 "firstprivate var already registered as private");
418 // Silence the warning about unused variable.
419 (void)IsRegistered;
420 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000421 ++IRef, ++InitsRef;
422 }
423 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000424 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000425}
426
Alexey Bataev03b340a2014-10-21 03:16:40 +0000427void CodeGenFunction::EmitOMPPrivateClause(
428 const OMPExecutableDirective &D,
429 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000430 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000431 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000432 auto IRef = C->varlist_begin();
433 for (auto IInit : C->private_copies()) {
434 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000435 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
436 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
437 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000438 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000439 // Emit private VarDecl with copy init.
440 EmitDecl(*VD);
441 return GetAddrOfLocalVar(VD);
442 });
443 assert(IsRegistered && "private var already registered as private");
444 // Silence the warning about unused variable.
445 (void)IsRegistered;
446 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000447 ++IRef;
448 }
449 }
450}
451
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000452bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
453 // threadprivate_var1 = master_threadprivate_var1;
454 // operator=(threadprivate_var2, master_threadprivate_var2);
455 // ...
456 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000457 llvm::DenseSet<const VarDecl *> CopiedVars;
458 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000459 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000460 auto IRef = C->varlist_begin();
461 auto ISrcRef = C->source_exprs().begin();
462 auto IDestRef = C->destination_exprs().begin();
463 for (auto *AssignOp : C->assignment_ops()) {
464 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000465 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000466 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000467
468 // Get the address of the master variable. If we are emitting code with
469 // TLS support, the address is passed from the master as field in the
470 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000471 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000472 if (getLangOpts().OpenMPUseTLS &&
473 getContext().getTargetInfo().isTLSSupported()) {
474 assert(CapturedStmtInfo->lookup(VD) &&
475 "Copyin threadprivates should have been captured!");
476 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
477 VK_LValue, (*IRef)->getExprLoc());
478 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000479 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000480 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000481 MasterAddr =
482 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
483 : CGM.GetAddrOfGlobal(VD),
484 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000485 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000486 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000487 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000488 if (CopiedVars.size() == 1) {
489 // At first check if current thread is a master thread. If it is, no
490 // need to copy data.
491 CopyBegin = createBasicBlock("copyin.not.master");
492 CopyEnd = createBasicBlock("copyin.not.master.end");
493 Builder.CreateCondBr(
494 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000495 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
496 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000497 CopyBegin, CopyEnd);
498 EmitBlock(CopyBegin);
499 }
500 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
501 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000502 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000503 }
504 ++IRef;
505 ++ISrcRef;
506 ++IDestRef;
507 }
508 }
509 if (CopyEnd) {
510 // Exit out of copying procedure for non-master thread.
511 EmitBlock(CopyEnd, /*IsFinished=*/true);
512 return true;
513 }
514 return false;
515}
516
Alexey Bataev38e89532015-04-16 04:54:05 +0000517bool CodeGenFunction::EmitOMPLastprivateClauseInit(
518 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000519 bool HasAtLeastOneLastprivate = false;
520 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000521 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000522 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000523 auto IRef = C->varlist_begin();
524 auto IDestRef = C->destination_exprs().begin();
525 for (auto *IInit : C->private_copies()) {
526 // Keep the address of the original variable for future update at the end
527 // of the loop.
528 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
529 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
530 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000531 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000532 DeclRefExpr DRE(
533 const_cast<VarDecl *>(OrigVD),
534 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
535 OrigVD) != nullptr,
536 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
537 return EmitLValue(&DRE).getAddress();
538 });
539 // Check if the variable is also a firstprivate: in this case IInit is
540 // not generated. Initialization of this variable will happen in codegen
541 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000542 if (IInit) {
543 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
544 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000545 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000546 // Emit private VarDecl with copy init.
547 EmitDecl(*VD);
548 return GetAddrOfLocalVar(VD);
549 });
550 assert(IsRegistered &&
551 "lastprivate var already registered as private");
552 (void)IsRegistered;
553 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000554 }
555 ++IRef, ++IDestRef;
556 }
557 }
558 return HasAtLeastOneLastprivate;
559}
560
561void CodeGenFunction::EmitOMPLastprivateClauseFinal(
562 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
563 // Emit following code:
564 // if (<IsLastIterCond>) {
565 // orig_var1 = private_orig_var1;
566 // ...
567 // orig_varn = private_orig_varn;
568 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000569 llvm::BasicBlock *ThenBB = nullptr;
570 llvm::BasicBlock *DoneBB = nullptr;
571 if (IsLastIterCond) {
572 ThenBB = createBasicBlock(".omp.lastprivate.then");
573 DoneBB = createBasicBlock(".omp.lastprivate.done");
574 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
575 EmitBlock(ThenBB);
576 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000577 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
578 const Expr *LastIterVal = nullptr;
579 const Expr *IVExpr = nullptr;
580 const Expr *IncExpr = nullptr;
581 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000582 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
583 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
584 LoopDirective->getUpperBoundVariable())
585 ->getDecl())
586 ->getAnyInitializer();
587 IVExpr = LoopDirective->getIterationVariable();
588 IncExpr = LoopDirective->getInc();
589 auto IUpdate = LoopDirective->updates().begin();
590 for (auto *E : LoopDirective->counters()) {
591 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
592 LoopCountersAndUpdates[D] = *IUpdate;
593 ++IUpdate;
594 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000595 }
596 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000597 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000598 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000599 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000600 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000601 auto IRef = C->varlist_begin();
602 auto ISrcRef = C->source_exprs().begin();
603 auto IDestRef = C->destination_exprs().begin();
604 for (auto *AssignOp : C->assignment_ops()) {
605 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000606 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000607 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
608 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
609 // If lastprivate variable is a loop control variable for loop-based
610 // directive, update its value before copyin back to original
611 // variable.
612 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000613 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000614 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
615 IVExpr->getType().getQualifiers(),
616 /*IsInitializer=*/false);
617 EmitIgnoredExpr(IncExpr);
618 FirstLCV = false;
619 }
620 EmitIgnoredExpr(UpExpr);
621 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000622 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
623 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
624 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000625 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000626 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000627 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
628 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000629 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000630 Address(Builder.CreateLoad(PrivateAddr),
631 getNaturalTypeAlignment(RefTy->getPointeeType()));
632 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000633 }
634 ++IRef;
635 ++ISrcRef;
636 ++IDestRef;
637 }
638 }
639 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000640 if (IsLastIterCond) {
641 EmitBlock(DoneBB, /*IsFinished=*/true);
642 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000643}
644
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000645void CodeGenFunction::EmitOMPReductionClauseInit(
646 const OMPExecutableDirective &D,
647 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000648 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000649 auto ILHS = C->lhs_exprs().begin();
650 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000651 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000652 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000653 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000654 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
655 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
656 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
657 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
658 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
659 Base = TempOASE->getBase()->IgnoreParenImpCasts();
660 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
661 Base = TempASE->getBase()->IgnoreParenImpCasts();
662 auto *DE = cast<DeclRefExpr>(Base);
663 auto *OrigVD = cast<VarDecl>(DE->getDecl());
664 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
665 auto OASELValueUB =
666 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
667 auto OriginalBaseLValue = EmitLValue(DE);
668 auto BaseLValue = OriginalBaseLValue;
669 auto *Zero = Builder.getInt64(/*C=*/0);
670 llvm::SmallVector<llvm::Value *, 4> Indexes;
671 Indexes.push_back(Zero);
672 auto *ItemTy =
673 OASELValueLB.getPointer()->getType()->getPointerElementType();
674 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
675 while (Ty != ItemTy) {
676 Indexes.push_back(Zero);
677 Ty = Ty->getPointerElementType();
678 }
679 BaseLValue = MakeAddrLValue(
680 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
681 OASELValueLB.getAlignment()),
682 OASELValueLB.getType(), OASELValueLB.getAlignmentSource());
683 // Store the address of the original variable associated with the LHS
684 // implicit variable.
685 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
686 return OASELValueLB.getAddress();
687 });
688 // Emit reduction copy.
689 bool IsRegistered = PrivateScope.addPrivate(
690 OrigVD, [this, PrivateVD, BaseLValue, OASELValueLB, OASELValueUB,
691 OriginalBaseLValue]() -> Address {
692 // Emit VarDecl with copy init for arrays.
693 // Get the address of the original variable captured in current
694 // captured region.
695 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
696 OASELValueLB.getPointer());
697 Size = Builder.CreateNUWAdd(
698 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
699 CodeGenFunction::OpaqueValueMapping OpaqueMap(
700 *this, cast<OpaqueValueExpr>(
701 getContext()
702 .getAsVariableArrayType(PrivateVD->getType())
703 ->getSizeExpr()),
704 RValue::get(Size));
705 EmitVariablyModifiedType(PrivateVD->getType());
706 auto Emission = EmitAutoVarAlloca(*PrivateVD);
707 auto Addr = Emission.getAllocatedAddress();
708 auto *Init = PrivateVD->getInit();
709 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
710 EmitAutoVarCleanups(Emission);
711 // Emit private VarDecl with reduction init.
712 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
713 OASELValueLB.getPointer());
714 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
715 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
716 Ptr, OriginalBaseLValue.getPointer()->getType());
717 return Address(Ptr, OriginalBaseLValue.getAlignment());
718 });
719 assert(IsRegistered && "private var already registered as private");
720 // Silence the warning about unused variable.
721 (void)IsRegistered;
722 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
723 return GetAddrOfLocalVar(PrivateVD);
724 });
725 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
726 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
727 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
728 Base = TempASE->getBase()->IgnoreParenImpCasts();
729 auto *DE = cast<DeclRefExpr>(Base);
730 auto *OrigVD = cast<VarDecl>(DE->getDecl());
731 auto ASELValue = EmitLValue(ASE);
732 auto OriginalBaseLValue = EmitLValue(DE);
733 auto BaseLValue = OriginalBaseLValue;
734 auto *Zero = Builder.getInt64(/*C=*/0);
735 llvm::SmallVector<llvm::Value *, 4> Indexes;
736 Indexes.push_back(Zero);
737 auto *ItemTy =
738 ASELValue.getPointer()->getType()->getPointerElementType();
739 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
740 while (Ty != ItemTy) {
741 Indexes.push_back(Zero);
742 Ty = Ty->getPointerElementType();
743 }
744 BaseLValue = MakeAddrLValue(
745 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
746 ASELValue.getAlignment()),
747 ASELValue.getType(), ASELValue.getAlignmentSource());
748 // Store the address of the original variable associated with the LHS
749 // implicit variable.
750 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
751 return ASELValue.getAddress();
752 });
753 // Emit reduction copy.
754 bool IsRegistered = PrivateScope.addPrivate(
755 OrigVD, [this, PrivateVD, BaseLValue, ASELValue,
756 OriginalBaseLValue]() -> Address {
757 // Emit private VarDecl with reduction init.
758 EmitDecl(*PrivateVD);
759 auto Addr = GetAddrOfLocalVar(PrivateVD);
760 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
761 ASELValue.getPointer());
762 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
763 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
764 Ptr, OriginalBaseLValue.getPointer()->getType());
765 return Address(Ptr, OriginalBaseLValue.getAlignment());
766 });
767 assert(IsRegistered && "private var already registered as private");
768 // Silence the warning about unused variable.
769 (void)IsRegistered;
770 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
771 return GetAddrOfLocalVar(PrivateVD);
772 });
773 } else {
774 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
775 // Store the address of the original variable associated with the LHS
776 // implicit variable.
777 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
778 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
779 CapturedStmtInfo->lookup(OrigVD) != nullptr,
780 IRef->getType(), VK_LValue, IRef->getExprLoc());
781 return EmitLValue(&DRE).getAddress();
782 });
783 // Emit reduction copy.
784 bool IsRegistered =
785 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
786 // Emit private VarDecl with reduction init.
787 EmitDecl(*PrivateVD);
788 return GetAddrOfLocalVar(PrivateVD);
789 });
790 assert(IsRegistered && "private var already registered as private");
791 // Silence the warning about unused variable.
792 (void)IsRegistered;
793 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
794 return GetAddrOfLocalVar(PrivateVD);
795 });
796 }
797 ++ILHS, ++IRHS, ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000798 }
799 }
800}
801
802void CodeGenFunction::EmitOMPReductionClauseFinal(
803 const OMPExecutableDirective &D) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000804 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000805 llvm::SmallVector<const Expr *, 8> LHSExprs;
806 llvm::SmallVector<const Expr *, 8> RHSExprs;
807 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000808 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000809 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000810 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000811 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000812 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
813 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
814 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
815 }
816 if (HasAtLeastOneReduction) {
817 // Emit nowait reduction if nowait clause is present or directive is a
818 // parallel directive (it always has implicit barrier).
819 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000820 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000821 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000822 isOpenMPParallelDirective(D.getDirectiveKind()) ||
823 D.getDirectiveKind() == OMPD_simd,
824 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000825 }
826}
827
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000828static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
829 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000830 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000831 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000832 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000833 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
834 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000835 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000836 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000837 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000838 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000839 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
840 /*IgnoreResultAssign*/ true);
841 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
842 CGF, NumThreads, NumThreadsClause->getLocStart());
843 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000844 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000845 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000846 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
847 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
848 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000849 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000850 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
851 if (C->getNameModifier() == OMPD_unknown ||
852 C->getNameModifier() == OMPD_parallel) {
853 IfCond = C->getCondition();
854 break;
855 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000856 }
857 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000858 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000859}
860
861void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
862 LexicalScope Scope(*this, S.getSourceRange());
863 // Emit parallel region as a standalone region.
864 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
865 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000866 bool Copyins = CGF.EmitOMPCopyinClause(S);
867 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
868 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000869 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000870 // initialization of firstprivate variables or propagation master's thread
871 // values of threadprivate variables to local instances of that variables
872 // of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000873 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
874 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
875 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000876 }
877 CGF.EmitOMPPrivateClause(S, PrivateScope);
878 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
879 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000880 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000881 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000882 // Emit implicit barrier at the end of the 'parallel' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000883 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
884 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
885 /*ForceSimpleCall=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000886 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000887 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000888}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000889
Alexey Bataev0f34da12015-07-02 04:17:07 +0000890void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
891 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000892 RunCleanupsScope BodyScope(*this);
893 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000894 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000895 EmitIgnoredExpr(I);
896 }
Alexander Musman3276a272015-03-21 10:12:56 +0000897 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000898 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000899 for (auto U : C->updates()) {
900 EmitIgnoredExpr(U);
901 }
902 }
903
Alexander Musmana5f070a2014-10-01 06:03:56 +0000904 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000905 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000906 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000907 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000908 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000909 // The end (updates/cleanups).
910 EmitBlock(Continue.getBlock());
911 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000912 // TODO: Update lastprivates if the SeparateIter flag is true.
913 // This will be implemented in a follow-up OMPLastprivateClause patch, but
914 // result should be still correct without it, as we do not make these
915 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000916}
917
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000918void CodeGenFunction::EmitOMPInnerLoop(
919 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
920 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000921 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
922 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000923 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000924
925 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000926 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000927 EmitBlock(CondBlock);
928 LoopStack.push(CondBlock);
929
930 // If there are any cleanups between here and the loop-exit scope,
931 // create a block to stage a loop exit along.
932 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000933 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000934 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000935
Alexander Musmand196ef22014-10-07 08:57:09 +0000936 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000937
Alexey Bataev2df54a02015-03-12 08:53:29 +0000938 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000939 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000940 if (ExitBlock != LoopExit.getBlock()) {
941 EmitBlock(ExitBlock);
942 EmitBranchThroughCleanup(LoopExit);
943 }
944
945 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000946 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000947
948 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000949 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000950 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
951
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000952 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000953
954 // Emit "IV = IV + 1" and a back-edge to the condition block.
955 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000956 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000957 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000958 BreakContinueStack.pop_back();
959 EmitBranch(CondBlock);
960 LoopStack.pop();
961 // Emit the fall-through block.
962 EmitBlock(LoopExit.getBlock());
963}
964
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000965void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000966 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000967 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000968 for (auto Init : C->inits()) {
969 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000970 auto *OrigVD = cast<VarDecl>(
971 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
972 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
973 CapturedStmtInfo->lookup(OrigVD) != nullptr,
974 VD->getInit()->getType(), VK_LValue,
975 VD->getInit()->getExprLoc());
976 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
977 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +0000978 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000979 /*capturedByInit=*/false);
980 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000981 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000982 // Emit the linear steps for the linear clauses.
983 // If a step is not constant, it is pre-calculated before the loop.
984 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
985 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000986 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000987 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000988 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000989 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000990 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000991}
992
993static void emitLinearClauseFinal(CodeGenFunction &CGF,
994 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000995 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000996 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000997 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000998 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000999 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1000 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001001 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001002 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001003 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001004 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001005 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001006 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001007 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001008 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001009 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001010 }
1011 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001012}
1013
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001014static void emitAlignedClause(CodeGenFunction &CGF,
1015 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001016 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001017 unsigned ClauseAlignment = 0;
1018 if (auto AlignmentExpr = Clause->getAlignment()) {
1019 auto AlignmentCI =
1020 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1021 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001022 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001023 for (auto E : Clause->varlists()) {
1024 unsigned Alignment = ClauseAlignment;
1025 if (Alignment == 0) {
1026 // OpenMP [2.8.1, Description]
1027 // If no optional parameter is specified, implementation-defined default
1028 // alignments for SIMD instructions on the target platforms are assumed.
1029 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001030 CGF.getContext()
1031 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1032 E->getType()->getPointeeType()))
1033 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001034 }
1035 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1036 "alignment is not power of 2");
1037 if (Alignment != 0) {
1038 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1039 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1040 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001041 }
1042 }
1043}
1044
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001045static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001046 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001047 ArrayRef<Expr *> Counters,
1048 ArrayRef<Expr *> PrivateCounters) {
1049 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001050 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001051 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1052 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001053 Address Addr = Address::invalid();
1054 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001055 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001056 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001057 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001058 Addr = VarEmission.getAllocatedAddress();
1059 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001060 });
John McCall7f416cc2015-09-08 08:05:57 +00001061 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001062 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001063 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001064}
1065
Alexey Bataev62dbb972015-04-22 11:59:37 +00001066static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1067 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1068 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001069 {
1070 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001071 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1072 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001073 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001074 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001075 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001076 CGF.EmitIgnoredExpr(I);
1077 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001078 }
1079 // Check that loop is executed at least one time.
1080 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1081}
1082
Alexander Musman3276a272015-03-21 10:12:56 +00001083static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001084emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001085 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001086 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001087 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001088 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001089 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1090 auto *PrivateVD =
1091 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001092 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001093 // Emit private VarDecl with copy init.
1094 CGF.EmitVarDecl(*PrivateVD);
1095 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001096 });
1097 assert(IsRegistered && "linear var already registered as private");
1098 // Silence the warning about unused variable.
1099 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001100 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001101 }
1102 }
1103}
1104
Alexey Bataev45bfad52015-08-21 12:19:04 +00001105static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1106 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001107 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001108 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1109 /*ignoreResult=*/true);
1110 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1111 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1112 // In presence of finite 'safelen', it may be unsafe to mark all
1113 // the memory instructions parallel, because loop-carried
1114 // dependences of 'safelen' iterations are possible.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001115 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1116 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001117 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1118 /*ignoreResult=*/true);
1119 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001120 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001121 // In presence of finite 'safelen', it may be unsafe to mark all
1122 // the memory instructions parallel, because loop-carried
1123 // dependences of 'safelen' iterations are possible.
1124 CGF.LoopStack.setParallel(false);
1125 }
1126}
1127
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001128void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
1129 // Walk clauses and process safelen/lastprivate.
1130 LoopStack.setParallel();
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001131 LoopStack.setVectorizeEnable(true);
Alexey Bataev45bfad52015-08-21 12:19:04 +00001132 emitSimdlenSafelenClause(*this, D);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001133}
1134
1135void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
1136 auto IC = D.counters().begin();
1137 for (auto F : D.finals()) {
1138 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001139 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001140 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1141 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1142 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001143 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001144 OMPPrivateScope VarScope(*this);
1145 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001146 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001147 (void)VarScope.Privatize();
1148 EmitIgnoredExpr(F);
1149 }
1150 ++IC;
1151 }
1152 emitLinearClauseFinal(*this, D);
1153}
1154
Alexander Musman515ad8c2014-05-22 08:54:05 +00001155void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001156 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001157 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001158 // for (IV in 0..LastIteration) BODY;
1159 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001160 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001161 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001162
Alexey Bataev62dbb972015-04-22 11:59:37 +00001163 // Emit: if (PreCond) - begin.
1164 // If the condition constant folds and can be elided, avoid emitting the
1165 // whole loop.
1166 bool CondConstant;
1167 llvm::BasicBlock *ContBlock = nullptr;
1168 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1169 if (!CondConstant)
1170 return;
1171 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001172 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1173 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001174 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1175 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001176 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001177 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001178 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001179
1180 // Emit the loop iteration variable.
1181 const Expr *IVExpr = S.getIterationVariable();
1182 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1183 CGF.EmitVarDecl(*IVDecl);
1184 CGF.EmitIgnoredExpr(S.getInit());
1185
1186 // Emit the iterations count variable.
1187 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001188 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1190 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1191 // Emit calculation of the iterations count.
1192 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001193 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001194
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001195 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001197 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001198 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001199 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001200 {
1201 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001202 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1203 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001204 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001205 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001206 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001207 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001208 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001209 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1210 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001211 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001212 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001213 CGF.EmitStopPoint(&S);
1214 },
1215 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001216 // Emit final copy of the lastprivate variables at the end of loops.
1217 if (HasLastprivateClause) {
1218 CGF.EmitOMPLastprivateClauseFinal(S);
1219 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001220 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001221 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001222 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001223 // Emit: if (PreCond) - end.
1224 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001225 CGF.EmitBranch(ContBlock);
1226 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001227 }
1228 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001229 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001230}
1231
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001232void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
1233 const OMPLoopDirective &S,
1234 OMPPrivateScope &LoopScope,
John McCall7f416cc2015-09-08 08:05:57 +00001235 bool Ordered, Address LB,
1236 Address UB, Address ST,
1237 Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001238 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001239
1240 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001241 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001242
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001243 assert((Ordered ||
1244 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001245 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001246
1247 // Emit outer loop.
1248 //
1249 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001250 // When schedule(dynamic,chunk_size) is specified, the iterations are
1251 // distributed to threads in the team in chunks as the threads request them.
1252 // Each thread executes a chunk of iterations, then requests another chunk,
1253 // until no chunks remain to be distributed. Each chunk contains chunk_size
1254 // iterations, except for the last chunk to be distributed, which may have
1255 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1256 //
1257 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1258 // to threads in the team in chunks as the executing threads request them.
1259 // Each thread executes a chunk of iterations, then requests another chunk,
1260 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1261 // each chunk is proportional to the number of unassigned iterations divided
1262 // by the number of threads in the team, decreasing to 1. For a chunk_size
1263 // with value k (greater than 1), the size of each chunk is determined in the
1264 // same way, with the restriction that the chunks do not contain fewer than k
1265 // iterations (except for the last chunk to be assigned, which may have fewer
1266 // than k iterations).
1267 //
1268 // When schedule(auto) is specified, the decision regarding scheduling is
1269 // delegated to the compiler and/or runtime system. The programmer gives the
1270 // implementation the freedom to choose any possible mapping of iterations to
1271 // threads in the team.
1272 //
1273 // When schedule(runtime) is specified, the decision regarding scheduling is
1274 // deferred until run time, and the schedule and chunk size are taken from the
1275 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1276 // implementation defined
1277 //
1278 // while(__kmpc_dispatch_next(&LB, &UB)) {
1279 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001280 // while (idx <= UB) { BODY; ++idx;
1281 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1282 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001283 // }
1284 //
1285 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001286 // When schedule(static, chunk_size) is specified, iterations are divided into
1287 // chunks of size chunk_size, and the chunks are assigned to the threads in
1288 // the team in a round-robin fashion in the order of the thread number.
1289 //
1290 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1291 // while (idx <= UB) { BODY; ++idx; } // inner loop
1292 // LB = LB + ST;
1293 // UB = UB + ST;
1294 // }
1295 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001296
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001297 const Expr *IVExpr = S.getIterationVariable();
1298 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1299 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1300
John McCall7f416cc2015-09-08 08:05:57 +00001301 if (DynamicOrOrdered) {
1302 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1303 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1304 IVSize, IVSigned, Ordered, UBVal, Chunk);
1305 } else {
1306 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1307 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1308 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001309
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001310 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1311
1312 // Start the loop with a block that tests the condition.
1313 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1314 EmitBlock(CondBlock);
1315 LoopStack.push(CondBlock);
1316
1317 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001318 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001319 // UB = min(UB, GlobalUB)
1320 EmitIgnoredExpr(S.getEnsureUpperBound());
1321 // IV = LB
1322 EmitIgnoredExpr(S.getInit());
1323 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001324 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001325 } else {
1326 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1327 IL, LB, UB, ST);
1328 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001329
1330 // If there are any cleanups between here and the loop-exit scope,
1331 // create a block to stage a loop exit along.
1332 auto ExitBlock = LoopExit.getBlock();
1333 if (LoopScope.requiresCleanups())
1334 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1335
1336 auto LoopBody = createBasicBlock("omp.dispatch.body");
1337 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1338 if (ExitBlock != LoopExit.getBlock()) {
1339 EmitBlock(ExitBlock);
1340 EmitBranchThroughCleanup(LoopExit);
1341 }
1342 EmitBlock(LoopBody);
1343
Alexander Musman92bdaab2015-03-12 13:37:50 +00001344 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1345 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001346 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001347 EmitIgnoredExpr(S.getInit());
1348
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001349 // Create a block for the increment.
1350 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1351 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1352
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001353 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1354 // with dynamic/guided scheduling and without ordered clause.
1355 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
1356 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
1357 ScheduleKind == OMPC_SCHEDULE_guided) &&
1358 !Ordered);
1359 } else {
1360 EmitOMPSimdInit(S);
1361 }
1362
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001363 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001364 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1365 [&S, LoopExit](CodeGenFunction &CGF) {
1366 CGF.EmitOMPLoopBody(S, LoopExit);
1367 CGF.EmitStopPoint(&S);
1368 },
1369 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1370 if (Ordered) {
1371 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1372 CGF, Loc, IVSize, IVSigned);
1373 }
1374 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001375
1376 EmitBlock(Continue.getBlock());
1377 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001378 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001379 // Emit "LB = LB + Stride", "UB = UB + Stride".
1380 EmitIgnoredExpr(S.getNextLowerBound());
1381 EmitIgnoredExpr(S.getNextUpperBound());
1382 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001383
1384 EmitBranch(CondBlock);
1385 LoopStack.pop();
1386 // Emit the fall-through block.
1387 EmitBlock(LoopExit.getBlock());
1388
1389 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001390 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001391 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001392}
1393
Alexander Musmanc6388682014-12-15 07:07:06 +00001394/// \brief Emit a helper variable and return corresponding lvalue.
1395static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1396 const DeclRefExpr *Helper) {
1397 auto VDecl = cast<VarDecl>(Helper->getDecl());
1398 CGF.EmitVarDecl(*VDecl);
1399 return CGF.EmitLValue(Helper);
1400}
1401
Alexey Bataev040d5402015-05-12 08:35:28 +00001402static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1403emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1404 bool OuterRegion) {
1405 // Detect the loop schedule kind and chunk.
1406 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1407 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001408 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001409 ScheduleKind = C->getScheduleKind();
1410 if (const auto *Ch = C->getChunkSize()) {
1411 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1412 if (OuterRegion) {
1413 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1414 CGF.EmitVarDecl(*ImpVar);
1415 CGF.EmitStoreThroughLValue(
1416 CGF.EmitAnyExpr(Ch),
John McCall7f416cc2015-09-08 08:05:57 +00001417 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1418 ImpVar->getType()));
Alexey Bataev040d5402015-05-12 08:35:28 +00001419 } else {
1420 Ch = ImpRef;
1421 }
1422 }
1423 if (!C->getHelperChunkSize() || !OuterRegion) {
1424 Chunk = CGF.EmitScalarExpr(Ch);
1425 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001426 S.getIterationVariable()->getType(),
1427 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001428 }
1429 }
1430 }
1431 return std::make_pair(Chunk, ScheduleKind);
1432}
1433
Alexey Bataev38e89532015-04-16 04:54:05 +00001434bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001435 // Emit the loop iteration variable.
1436 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1437 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1438 EmitVarDecl(*IVDecl);
1439
1440 // Emit the iterations count variable.
1441 // If it is not a variable, Sema decided to calculate iterations count on each
1442 // iteration (e.g., it is foldable into a constant).
1443 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1444 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1445 // Emit calculation of the iterations count.
1446 EmitIgnoredExpr(S.getCalcLastIteration());
1447 }
1448
1449 auto &RT = CGM.getOpenMPRuntime();
1450
Alexey Bataev38e89532015-04-16 04:54:05 +00001451 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001452 // Check pre-condition.
1453 {
1454 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001455 // If the condition constant folds and can be elided, avoid emitting the
1456 // whole loop.
1457 bool CondConstant;
1458 llvm::BasicBlock *ContBlock = nullptr;
1459 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1460 if (!CondConstant)
1461 return false;
1462 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001463 auto *ThenBlock = createBasicBlock("omp.precond.then");
1464 ContBlock = createBasicBlock("omp.precond.end");
1465 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001466 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001467 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001468 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001469 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001470
1471 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001472 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001473 // Emit 'then' code.
1474 {
1475 // Emit helper vars inits.
1476 LValue LB =
1477 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1478 LValue UB =
1479 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1480 LValue ST =
1481 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1482 LValue IL =
1483 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1484
1485 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001486 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1487 // Emit implicit barrier to synchronize threads and avoid data races on
1488 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001489 CGM.getOpenMPRuntime().emitBarrierCall(
1490 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1491 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001492 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001493 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001494 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001495 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001496 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1497 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001498 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001499 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001500
1501 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001502 llvm::Value *Chunk;
1503 OpenMPScheduleClauseKind ScheduleKind;
1504 auto ScheduleInfo =
1505 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1506 Chunk = ScheduleInfo.first;
1507 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001508 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1509 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001510 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001511 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001512 /* Chunked */ Chunk != nullptr) &&
1513 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001514 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1515 EmitOMPSimdInit(S);
1516 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001517 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1518 // When no chunk_size is specified, the iteration space is divided into
1519 // chunks that are approximately equal in size, and at most one chunk is
1520 // distributed to each thread. Note that the size of the chunks is
1521 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001522 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1523 IVSize, IVSigned, Ordered,
1524 IL.getAddress(), LB.getAddress(),
1525 UB.getAddress(), ST.getAddress());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001526 auto LoopExit = getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001527 // UB = min(UB, GlobalUB);
1528 EmitIgnoredExpr(S.getEnsureUpperBound());
1529 // IV = LB;
1530 EmitIgnoredExpr(S.getInit());
1531 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001532 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1533 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001534 [&S, LoopExit](CodeGenFunction &CGF) {
1535 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001536 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001537 },
1538 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001539 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001540 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001541 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001542 } else {
1543 // Emit the outer loop, which requests its work chunk [LB..UB] from
1544 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001545 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1546 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1547 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001548 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001549 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001550 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1551 if (HasLastprivateClause)
1552 EmitOMPLastprivateClauseFinal(
1553 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001554 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001555 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1556 EmitOMPSimdFinal(S);
1557 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001558 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001559 if (ContBlock) {
1560 EmitBranch(ContBlock);
1561 EmitBlock(ContBlock, true);
1562 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001563 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001564 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001565}
1566
1567void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001568 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001569 bool HasLastprivates = false;
1570 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1571 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1572 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001573 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1574 S.hasCancel());
Alexander Musmanc6388682014-12-15 07:07:06 +00001575
1576 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001577 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001578 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1579 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001580}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001581
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001582void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1583 LexicalScope Scope(*this, S.getSourceRange());
1584 bool HasLastprivates = false;
1585 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1586 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1587 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001588 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001589
1590 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001591 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001592 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1593 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001594}
1595
Alexey Bataev2df54a02015-03-12 08:53:29 +00001596static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1597 const Twine &Name,
1598 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001599 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001600 if (Init)
1601 CGF.EmitScalarInit(Init, LVal);
1602 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001603}
1604
Alexey Bataev0f34da12015-07-02 04:17:07 +00001605OpenMPDirectiveKind
1606CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001607 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1608 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1609 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001610 bool HasLastprivates = false;
1611 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001612 auto &C = CGF.CGM.getContext();
1613 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1614 // Emit helper vars inits.
1615 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1616 CGF.Builder.getInt32(0));
1617 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1618 LValue UB =
1619 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1620 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1621 CGF.Builder.getInt32(1));
1622 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1623 CGF.Builder.getInt32(0));
1624 // Loop counter.
1625 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1626 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001627 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001628 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001629 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001630 // Generate condition for loop.
1631 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1632 OK_Ordinary, S.getLocStart(),
1633 /*fpContractable=*/false);
1634 // Increment for loop counter.
1635 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1636 OK_Ordinary, S.getLocStart());
1637 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1638 // Iterate through all sections and emit a switch construct:
1639 // switch (IV) {
1640 // case 0:
1641 // <SectionStmt[0]>;
1642 // break;
1643 // ...
1644 // case <NumSection> - 1:
1645 // <SectionStmt[<NumSection> - 1]>;
1646 // break;
1647 // }
1648 // .omp.sections.exit:
1649 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1650 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1651 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1652 CS->size());
1653 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001654 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001655 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1656 CGF.EmitBlock(CaseBB);
1657 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001658 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001659 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001660 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001661 }
1662 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1663 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001664
1665 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1666 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1667 // Emit implicit barrier to synchronize threads and avoid data races on
1668 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001669 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1670 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1671 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001672 }
Alexey Bataev73870832015-04-27 04:12:12 +00001673 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001674 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001675 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001676 (void)LoopScope.Privatize();
1677
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001678 // Emit static non-chunked loop.
John McCall7f416cc2015-09-08 08:05:57 +00001679 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001680 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001681 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1682 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001683 // UB = min(UB, GlobalUB);
1684 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1685 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1686 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1687 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1688 // IV = LB;
1689 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1690 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001691 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1692 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001693 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001694 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001695 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001696
1697 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1698 if (HasLastprivates)
1699 CGF.EmitOMPLastprivateClauseFinal(
1700 S, CGF.Builder.CreateIsNotNull(
1701 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001702 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001703
Alexey Bataev25e5b442015-09-15 12:52:43 +00001704 bool HasCancel = false;
1705 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1706 HasCancel = OSD->hasCancel();
1707 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1708 HasCancel = OPSD->hasCancel();
1709 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1710 HasCancel);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001711 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1712 // clause. Otherwise the barrier will be generated by the codegen for the
1713 // directive.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001714 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001715 // Emit implicit barrier to synchronize threads and avoid data races on
1716 // initialization of firstprivate variables.
Alexey Bataev0f34da12015-07-02 04:17:07 +00001717 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1718 OMPD_unknown);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001719 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001720 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001721 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001722 // If only one section is found - no need to generate loop, emit as a single
1723 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001724 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001725 // No need to generate reductions for sections with single section region, we
1726 // can use original shared variables for all operations.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001727 bool HasReductions = S.hasClausesOfKind<OMPReductionClause>();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001728 // No need to generate lastprivates for sections with single section region,
1729 // we can use original shared variable for all calculations with barrier at
1730 // the end of the sections.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001731 bool HasLastprivates = S.hasClausesOfKind<OMPLastprivateClause>();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001732 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1733 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1734 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001735 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001736 (void)SingleScope.Privatize();
1737
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001738 CGF.EmitStmt(Stmt);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001739 };
Alexey Bataev0f34da12015-07-02 04:17:07 +00001740 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1741 llvm::None, llvm::None, llvm::None,
1742 llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001743 // Emit barrier for firstprivates, lastprivates or reductions only if
1744 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1745 // generated by the codegen for the directive.
1746 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001747 S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001748 // Emit implicit barrier to synchronize threads and avoid data races on
1749 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001750 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown,
1751 /*EmitChecks=*/false,
1752 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001753 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001754 return OMPD_single;
1755}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001756
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001757void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1758 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001759 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001760 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001761 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001762 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001763 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001764}
1765
1766void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001767 LexicalScope Scope(*this, S.getSourceRange());
1768 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1769 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1770 CGF.EnsureInsertPoint();
1771 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001772 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1773 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001774}
1775
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001776void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001777 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001778 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001779 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001780 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001781 // Check if there are any 'copyprivate' clauses associated with this
1782 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001783 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001784 // Build a list of copyprivate variables along with helper expressions
1785 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001786 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001787 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001788 DestExprs.append(C->destination_exprs().begin(),
1789 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001790 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001791 AssignmentOps.append(C->assignment_ops().begin(),
1792 C->assignment_ops().end());
1793 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001794 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001795 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001796 bool HasFirstprivates;
1797 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1798 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1799 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001800 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001801 (void)SingleScope.Privatize();
1802
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001803 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1804 CGF.EnsureInsertPoint();
1805 };
1806 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001807 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001808 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001809 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1810 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001811 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001812 CopyprivateVars.empty()) {
1813 CGM.getOpenMPRuntime().emitBarrierCall(
1814 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001815 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001816 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001817}
1818
Alexey Bataev8d690652014-12-04 07:23:53 +00001819void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001820 LexicalScope Scope(*this, S.getSourceRange());
1821 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1822 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1823 CGF.EnsureInsertPoint();
1824 };
1825 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001826}
1827
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001828void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001829 LexicalScope Scope(*this, S.getSourceRange());
1830 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1831 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1832 CGF.EnsureInsertPoint();
1833 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001834 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001835 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001836}
1837
Alexey Bataev671605e2015-04-13 05:28:11 +00001838void CodeGenFunction::EmitOMPParallelForDirective(
1839 const OMPParallelForDirective &S) {
1840 // Emit directive as a combined directive that consists of two implicit
1841 // directives: 'parallel' with 'for' directive.
1842 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001843 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001844 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1845 CGF.EmitOMPWorksharingLoop(S);
1846 // Emit implicit barrier at the end of parallel region, but this barrier
1847 // is at the end of 'for' directive, so emit it as the implicit barrier for
1848 // this 'for' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001849 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1850 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1851 /*ForceSimpleCall=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001852 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001853 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001854}
1855
Alexander Musmane4e893b2014-09-23 09:33:00 +00001856void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001857 const OMPParallelForSimdDirective &S) {
1858 // Emit directive as a combined directive that consists of two implicit
1859 // directives: 'parallel' with 'for' directive.
1860 LexicalScope Scope(*this, S.getSourceRange());
1861 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1862 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1863 CGF.EmitOMPWorksharingLoop(S);
1864 // Emit implicit barrier at the end of parallel region, but this barrier
1865 // is at the end of 'for' directive, so emit it as the implicit barrier for
1866 // this 'for' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001867 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1868 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1869 /*ForceSimpleCall=*/true);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001870 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001871 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001872}
1873
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001874void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001875 const OMPParallelSectionsDirective &S) {
1876 // Emit directive as a combined directive that consists of two implicit
1877 // directives: 'parallel' with 'sections' directive.
1878 LexicalScope Scope(*this, S.getSourceRange());
1879 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001880 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001881 // Emit implicit barrier at the end of parallel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001882 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1883 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1884 /*ForceSimpleCall=*/true);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001885 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001886 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001887}
1888
Alexey Bataev62b63b12015-03-10 07:28:44 +00001889void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1890 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001891 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001892 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1893 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1894 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001895 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001896 // The first function argument for tasks is a thread id, the second one is a
1897 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001898 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1899 // Get list of private variables.
1900 llvm::SmallVector<const Expr *, 8> PrivateVars;
1901 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001902 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001903 auto IRef = C->varlist_begin();
1904 for (auto *IInit : C->private_copies()) {
1905 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1906 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1907 PrivateVars.push_back(*IRef);
1908 PrivateCopies.push_back(IInit);
1909 }
1910 ++IRef;
1911 }
1912 }
1913 EmittedAsPrivate.clear();
1914 // Get list of firstprivate variables.
1915 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1916 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1917 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001918 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001919 auto IRef = C->varlist_begin();
1920 auto IElemInitRef = C->inits().begin();
1921 for (auto *IInit : C->private_copies()) {
1922 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1923 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1924 FirstprivateVars.push_back(*IRef);
1925 FirstprivateCopies.push_back(IInit);
1926 FirstprivateInits.push_back(*IElemInitRef);
1927 }
1928 ++IRef, ++IElemInitRef;
1929 }
1930 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001931 // Build list of dependences.
1932 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1933 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001934 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001935 for (auto *IRef : C->varlists()) {
1936 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1937 }
1938 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001939 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1940 CodeGenFunction &CGF) {
1941 // Set proper addresses for generated private copies.
1942 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1943 OMPPrivateScope Scope(CGF);
1944 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00001945 auto *CopyFn = CGF.Builder.CreateLoad(
1946 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
1947 auto *PrivatesPtr = CGF.Builder.CreateLoad(
1948 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001949 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00001950 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001951 PrivatePtrs;
1952 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1953 CallArgs.push_back(PrivatesPtr);
1954 for (auto *E : PrivateVars) {
1955 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001956 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001957 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1958 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001959 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001960 }
1961 for (auto *E : FirstprivateVars) {
1962 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001963 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001964 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1965 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001966 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001967 }
1968 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1969 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00001970 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
1971 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001972 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1973 }
1974 }
1975 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001976 if (*PartId) {
1977 // TODO: emit code for untied tasks.
1978 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001979 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001980 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001981 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
1982 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001983 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001984 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001985 // Check if the task is final
1986 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001987 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001988 // If the condition constant folds and can be elided, try to avoid emitting
1989 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001990 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001991 bool CondConstant;
1992 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1993 Final.setInt(CondConstant);
1994 else
1995 Final.setPointer(EvaluateExprAsBool(Cond));
1996 } else {
1997 // By default the task is not final.
1998 Final.setInt(/*IntVal=*/false);
1999 }
2000 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002001 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002002 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2003 if (C->getNameModifier() == OMPD_unknown ||
2004 C->getNameModifier() == OMPD_task) {
2005 IfCond = C->getCondition();
2006 break;
2007 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002008 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002009 CGM.getOpenMPRuntime().emitTaskCall(
2010 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002011 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002012 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002013}
2014
Alexey Bataev9f797f32015-02-05 05:57:51 +00002015void CodeGenFunction::EmitOMPTaskyieldDirective(
2016 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002017 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002018}
2019
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002020void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002021 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002022}
2023
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002024void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2025 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002026}
2027
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002028void CodeGenFunction::EmitOMPTaskgroupDirective(
2029 const OMPTaskgroupDirective &S) {
2030 LexicalScope Scope(*this, S.getSourceRange());
2031 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2032 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2033 CGF.EnsureInsertPoint();
2034 };
2035 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2036}
2037
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002038void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002039 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002040 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002041 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2042 FlushClause->varlist_end());
2043 }
2044 return llvm::None;
2045 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002046}
2047
Alexey Bataev5f600d62015-09-29 03:48:57 +00002048static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2049 const CapturedStmt *S) {
2050 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2051 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2052 CGF.CapturedStmtInfo = &CapStmtInfo;
2053 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2054 Fn->addFnAttr(llvm::Attribute::NoInline);
2055 return Fn;
2056}
2057
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002058void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
2059 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev5f600d62015-09-29 03:48:57 +00002060 auto *C = S.getSingleClause<OMPSIMDClause>();
2061 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2062 if (C) {
2063 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2064 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2065 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2066 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2067 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2068 } else {
2069 CGF.EmitStmt(
2070 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2071 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002072 CGF.EnsureInsertPoint();
2073 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002074 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002075}
2076
Alexey Bataevb57056f2015-01-22 06:17:56 +00002077static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002078 QualType SrcType, QualType DestType,
2079 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002080 assert(CGF.hasScalarEvaluationKind(DestType) &&
2081 "DestType must have scalar evaluation kind.");
2082 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2083 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002084 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2085 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002086 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002087 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002088}
2089
2090static CodeGenFunction::ComplexPairTy
2091convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002092 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002093 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2094 "DestType must have complex evaluation kind.");
2095 CodeGenFunction::ComplexPairTy ComplexVal;
2096 if (Val.isScalar()) {
2097 // Convert the input element to the element type of the complex.
2098 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002099 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2100 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002101 ComplexVal = CodeGenFunction::ComplexPairTy(
2102 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2103 } else {
2104 assert(Val.isComplex() && "Must be a scalar or complex.");
2105 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2106 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2107 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002108 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002109 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002110 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002111 }
2112 return ComplexVal;
2113}
2114
Alexey Bataev5e018f92015-04-23 06:35:10 +00002115static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2116 LValue LVal, RValue RVal) {
2117 if (LVal.isGlobalReg()) {
2118 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2119 } else {
2120 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2121 : llvm::Monotonic,
2122 LVal.isVolatile(), /*IsInit=*/false);
2123 }
2124}
2125
2126static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002127 QualType RValTy, SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002128 switch (CGF.getEvaluationKind(LVal.getType())) {
2129 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002130 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2131 CGF, RVal, RValTy, LVal.getType(), Loc)),
2132 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002133 break;
2134 case TEK_Complex:
2135 CGF.EmitStoreOfComplex(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002136 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002137 /*isInit=*/false);
2138 break;
2139 case TEK_Aggregate:
2140 llvm_unreachable("Must be a scalar or complex.");
2141 }
2142}
2143
Alexey Bataevb57056f2015-01-22 06:17:56 +00002144static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2145 const Expr *X, const Expr *V,
2146 SourceLocation Loc) {
2147 // v = x;
2148 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2149 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2150 LValue XLValue = CGF.EmitLValue(X);
2151 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002152 RValue Res = XLValue.isGlobalReg()
2153 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2154 : CGF.EmitAtomicLoad(XLValue, Loc,
2155 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002156 : llvm::Monotonic,
2157 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002158 // OpenMP, 2.12.6, atomic Construct
2159 // Any atomic construct with a seq_cst clause forces the atomically
2160 // performed operation to include an implicit flush operation without a
2161 // list.
2162 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002163 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002164 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002165}
2166
Alexey Bataevb8329262015-02-27 06:33:30 +00002167static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2168 const Expr *X, const Expr *E,
2169 SourceLocation Loc) {
2170 // x = expr;
2171 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002172 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002173 // OpenMP, 2.12.6, atomic Construct
2174 // Any atomic construct with a seq_cst clause forces the atomically
2175 // performed operation to include an implicit flush operation without a
2176 // list.
2177 if (IsSeqCst)
2178 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2179}
2180
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002181static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2182 RValue Update,
2183 BinaryOperatorKind BO,
2184 llvm::AtomicOrdering AO,
2185 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002186 auto &Context = CGF.CGM.getContext();
2187 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002188 // expression is simple and atomic is allowed for the given type for the
2189 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002190 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002191 !Update.getScalarVal()->getType()->isIntegerTy() ||
2192 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2193 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002194 X.getAddress().getElementType())) ||
2195 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002196 !Context.getTargetInfo().hasBuiltinAtomic(
2197 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002198 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002199
2200 llvm::AtomicRMWInst::BinOp RMWOp;
2201 switch (BO) {
2202 case BO_Add:
2203 RMWOp = llvm::AtomicRMWInst::Add;
2204 break;
2205 case BO_Sub:
2206 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002207 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002208 RMWOp = llvm::AtomicRMWInst::Sub;
2209 break;
2210 case BO_And:
2211 RMWOp = llvm::AtomicRMWInst::And;
2212 break;
2213 case BO_Or:
2214 RMWOp = llvm::AtomicRMWInst::Or;
2215 break;
2216 case BO_Xor:
2217 RMWOp = llvm::AtomicRMWInst::Xor;
2218 break;
2219 case BO_LT:
2220 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2221 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2222 : llvm::AtomicRMWInst::Max)
2223 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2224 : llvm::AtomicRMWInst::UMax);
2225 break;
2226 case BO_GT:
2227 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2228 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2229 : llvm::AtomicRMWInst::Min)
2230 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2231 : llvm::AtomicRMWInst::UMin);
2232 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002233 case BO_Assign:
2234 RMWOp = llvm::AtomicRMWInst::Xchg;
2235 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002236 case BO_Mul:
2237 case BO_Div:
2238 case BO_Rem:
2239 case BO_Shl:
2240 case BO_Shr:
2241 case BO_LAnd:
2242 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002243 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002244 case BO_PtrMemD:
2245 case BO_PtrMemI:
2246 case BO_LE:
2247 case BO_GE:
2248 case BO_EQ:
2249 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002250 case BO_AddAssign:
2251 case BO_SubAssign:
2252 case BO_AndAssign:
2253 case BO_OrAssign:
2254 case BO_XorAssign:
2255 case BO_MulAssign:
2256 case BO_DivAssign:
2257 case BO_RemAssign:
2258 case BO_ShlAssign:
2259 case BO_ShrAssign:
2260 case BO_Comma:
2261 llvm_unreachable("Unsupported atomic update operation");
2262 }
2263 auto *UpdateVal = Update.getScalarVal();
2264 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2265 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002266 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002267 X.getType()->hasSignedIntegerRepresentation());
2268 }
John McCall7f416cc2015-09-08 08:05:57 +00002269 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002270 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002271}
2272
Alexey Bataev5e018f92015-04-23 06:35:10 +00002273std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002274 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2275 llvm::AtomicOrdering AO, SourceLocation Loc,
2276 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2277 // Update expressions are allowed to have the following forms:
2278 // x binop= expr; -> xrval + expr;
2279 // x++, ++x -> xrval + 1;
2280 // x--, --x -> xrval - 1;
2281 // x = x binop expr; -> xrval binop expr
2282 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002283 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2284 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002285 if (X.isGlobalReg()) {
2286 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2287 // 'xrval'.
2288 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2289 } else {
2290 // Perform compare-and-swap procedure.
2291 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002292 }
2293 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002294 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002295}
2296
2297static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2298 const Expr *X, const Expr *E,
2299 const Expr *UE, bool IsXLHSInRHSPart,
2300 SourceLocation Loc) {
2301 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2302 "Update expr in 'atomic update' must be a binary operator.");
2303 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2304 // Update expressions are allowed to have the following forms:
2305 // x binop= expr; -> xrval + expr;
2306 // x++, ++x -> xrval + 1;
2307 // x--, --x -> xrval - 1;
2308 // x = x binop expr; -> xrval binop expr
2309 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002310 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002311 LValue XLValue = CGF.EmitLValue(X);
2312 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002313 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002314 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2315 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2316 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2317 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2318 auto Gen =
2319 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2320 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2321 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2322 return CGF.EmitAnyExpr(UE);
2323 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002324 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2325 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2326 // OpenMP, 2.12.6, atomic Construct
2327 // Any atomic construct with a seq_cst clause forces the atomically
2328 // performed operation to include an implicit flush operation without a
2329 // list.
2330 if (IsSeqCst)
2331 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2332}
2333
2334static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002335 QualType SourceType, QualType ResType,
2336 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002337 switch (CGF.getEvaluationKind(ResType)) {
2338 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002339 return RValue::get(
2340 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002341 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002342 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002343 return RValue::getComplex(Res.first, Res.second);
2344 }
2345 case TEK_Aggregate:
2346 break;
2347 }
2348 llvm_unreachable("Must be a scalar or complex.");
2349}
2350
2351static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2352 bool IsPostfixUpdate, const Expr *V,
2353 const Expr *X, const Expr *E,
2354 const Expr *UE, bool IsXLHSInRHSPart,
2355 SourceLocation Loc) {
2356 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2357 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2358 RValue NewVVal;
2359 LValue VLValue = CGF.EmitLValue(V);
2360 LValue XLValue = CGF.EmitLValue(X);
2361 RValue ExprRValue = CGF.EmitAnyExpr(E);
2362 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2363 QualType NewVValType;
2364 if (UE) {
2365 // 'x' is updated with some additional value.
2366 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2367 "Update expr in 'atomic capture' must be a binary operator.");
2368 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2369 // Update expressions are allowed to have the following forms:
2370 // x binop= expr; -> xrval + expr;
2371 // x++, ++x -> xrval + 1;
2372 // x--, --x -> xrval - 1;
2373 // x = x binop expr; -> xrval binop expr
2374 // x = expr Op x; - > expr binop xrval;
2375 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2376 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2377 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2378 NewVValType = XRValExpr->getType();
2379 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2380 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2381 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2382 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2383 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2384 RValue Res = CGF.EmitAnyExpr(UE);
2385 NewVVal = IsPostfixUpdate ? XRValue : Res;
2386 return Res;
2387 };
2388 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2389 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2390 if (Res.first) {
2391 // 'atomicrmw' instruction was generated.
2392 if (IsPostfixUpdate) {
2393 // Use old value from 'atomicrmw'.
2394 NewVVal = Res.second;
2395 } else {
2396 // 'atomicrmw' does not provide new value, so evaluate it using old
2397 // value of 'x'.
2398 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2399 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2400 NewVVal = CGF.EmitAnyExpr(UE);
2401 }
2402 }
2403 } else {
2404 // 'x' is simply rewritten with some 'expr'.
2405 NewVValType = X->getType().getNonReferenceType();
2406 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002407 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002408 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2409 NewVVal = XRValue;
2410 return ExprRValue;
2411 };
2412 // Try to perform atomicrmw xchg, otherwise simple exchange.
2413 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2414 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2415 Loc, Gen);
2416 if (Res.first) {
2417 // 'atomicrmw' instruction was generated.
2418 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2419 }
2420 }
2421 // Emit post-update store to 'v' of old/new 'x' value.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002422 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002423 // OpenMP, 2.12.6, atomic Construct
2424 // Any atomic construct with a seq_cst clause forces the atomically
2425 // performed operation to include an implicit flush operation without a
2426 // list.
2427 if (IsSeqCst)
2428 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2429}
2430
Alexey Bataevb57056f2015-01-22 06:17:56 +00002431static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002432 bool IsSeqCst, bool IsPostfixUpdate,
2433 const Expr *X, const Expr *V, const Expr *E,
2434 const Expr *UE, bool IsXLHSInRHSPart,
2435 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002436 switch (Kind) {
2437 case OMPC_read:
2438 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2439 break;
2440 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002441 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2442 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002443 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002444 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002445 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2446 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002447 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002448 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2449 IsXLHSInRHSPart, Loc);
2450 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002451 case OMPC_if:
2452 case OMPC_final:
2453 case OMPC_num_threads:
2454 case OMPC_private:
2455 case OMPC_firstprivate:
2456 case OMPC_lastprivate:
2457 case OMPC_reduction:
2458 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002459 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002460 case OMPC_collapse:
2461 case OMPC_default:
2462 case OMPC_seq_cst:
2463 case OMPC_shared:
2464 case OMPC_linear:
2465 case OMPC_aligned:
2466 case OMPC_copyin:
2467 case OMPC_copyprivate:
2468 case OMPC_flush:
2469 case OMPC_proc_bind:
2470 case OMPC_schedule:
2471 case OMPC_ordered:
2472 case OMPC_nowait:
2473 case OMPC_untied:
2474 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002475 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002476 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002477 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002478 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002479 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002480 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002481 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002482 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002483 case OMPC_priority:
Alexey Bataevb825de12015-12-07 10:51:44 +00002484 case OMPC_nogroup:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002485 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2486 }
2487}
2488
2489void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002490 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002491 OpenMPClauseKind Kind = OMPC_unknown;
2492 for (auto *C : S.clauses()) {
2493 // Find first clause (skip seq_cst clause, if it is first).
2494 if (C->getClauseKind() != OMPC_seq_cst) {
2495 Kind = C->getClauseKind();
2496 break;
2497 }
2498 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002499
2500 const auto *CS =
2501 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002502 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002503 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002504 }
2505 // Processing for statements under 'atomic capture'.
2506 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2507 for (const auto *C : Compound->body()) {
2508 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2509 enterFullExpression(EWC);
2510 }
2511 }
2512 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002513
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002514 LexicalScope Scope(*this, S.getSourceRange());
2515 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002516 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2517 S.getV(), S.getExpr(), S.getUpdateExpr(),
2518 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002519 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002520 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002521}
2522
Samuel Antaobed3c462015-10-02 16:14:20 +00002523void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
2524 LexicalScope Scope(*this, S.getSourceRange());
2525 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2526
2527 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002528 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002529
2530 // Emit target region as a standalone region.
2531 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
2532 CGF.EmitStmt(CS.getCapturedStmt());
2533 };
2534
2535 // Obtain the target region outlined function.
2536 llvm::Value *Fn =
2537 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, CodeGen);
2538
2539 // Check if we have any if clause associated with the directive.
2540 const Expr *IfCond = nullptr;
2541
2542 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2543 IfCond = C->getCondition();
2544 }
2545
2546 // Check if we have any device clause associated with the directive.
2547 const Expr *Device = nullptr;
2548 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2549 Device = C->getDevice();
2550 }
2551
2552 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, IfCond, Device,
2553 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002554}
2555
Alexey Bataev13314bf2014-10-09 04:18:56 +00002556void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2557 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2558}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002559
2560void CodeGenFunction::EmitOMPCancellationPointDirective(
2561 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002562 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2563 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002564}
2565
Alexey Bataev80909872015-07-02 11:25:17 +00002566void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002567 const Expr *IfCond = nullptr;
2568 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2569 if (C->getNameModifier() == OMPD_unknown ||
2570 C->getNameModifier() == OMPD_cancel) {
2571 IfCond = C->getCondition();
2572 break;
2573 }
2574 }
2575 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002576 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002577}
2578
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002579CodeGenFunction::JumpDest
2580CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2581 if (Kind == OMPD_parallel || Kind == OMPD_task)
2582 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002583 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
2584 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
2585 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002586}
Michael Wong65f367f2015-07-21 13:44:28 +00002587
2588// Generate the instructions for '#pragma omp target data' directive.
2589void CodeGenFunction::EmitOMPTargetDataDirective(
2590 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002591 // emit the code inside the construct for now
2592 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002593 CGM.getOpenMPRuntime().emitInlinedDirective(
2594 *this, OMPD_target_data,
2595 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002596}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002597
2598void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2599 // emit the code inside the construct for now
2600 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2601 CGM.getOpenMPRuntime().emitInlinedDirective(
2602 *this, OMPD_taskloop,
2603 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2604}
2605
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002606void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2607 const OMPTaskLoopSimdDirective &S) {
2608 // emit the code inside the construct for now
2609 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2610 CGM.getOpenMPRuntime().emitInlinedDirective(
2611 *this, OMPD_taskloop_simd,
2612 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2613}
2614