blob: f6b8e5907d47c114a8e12565140cf8ea0bba040d [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 Bataev8ef31412015-12-18 07:58:25 +0000357 if (!HaveInsertPoint())
358 return false;
Alexey Bataev69c62a92015-04-15 04:52:20 +0000359 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000360 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000361 auto IRef = C->varlist_begin();
362 auto InitsRef = C->inits().begin();
363 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000364 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000365 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
366 EmittedAsFirstprivate.insert(OrigVD);
367 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
368 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
369 bool IsRegistered;
370 DeclRefExpr DRE(
371 const_cast<VarDecl *>(OrigVD),
372 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
373 OrigVD) != nullptr,
374 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000375 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000376 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000377 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000378 // Emit VarDecl with copy init for arrays.
379 // Get the address of the original variable captured in current
380 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000381 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000382 auto Emission = EmitAutoVarAlloca(*VD);
383 auto *Init = VD->getInit();
384 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
385 // Perform simple memcpy.
386 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000387 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000388 } else {
389 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000390 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000391 [this, VDInit, Init](Address DestElement,
392 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000393 // Clean up any temporaries needed by the initialization.
394 RunCleanupsScope InitScope(*this);
395 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000396 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000397 EmitAnyExprToMem(Init, DestElement,
398 Init->getType().getQualifiers(),
399 /*IsInitializer*/ false);
400 LocalDeclMap.erase(VDInit);
401 });
402 }
403 EmitAutoVarCleanups(Emission);
404 return Emission.getAllocatedAddress();
405 });
406 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000407 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000408 // Emit private VarDecl with copy init.
409 // Remap temp VDInit variable to the address of the original
410 // variable
411 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000412 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000413 EmitDecl(*VD);
414 LocalDeclMap.erase(VDInit);
415 return GetAddrOfLocalVar(VD);
416 });
417 }
418 assert(IsRegistered &&
419 "firstprivate var already registered as private");
420 // Silence the warning about unused variable.
421 (void)IsRegistered;
422 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000423 ++IRef, ++InitsRef;
424 }
425 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000426 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000427}
428
Alexey Bataev03b340a2014-10-21 03:16:40 +0000429void CodeGenFunction::EmitOMPPrivateClause(
430 const OMPExecutableDirective &D,
431 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000432 if (!HaveInsertPoint())
433 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000434 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000435 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000436 auto IRef = C->varlist_begin();
437 for (auto IInit : C->private_copies()) {
438 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000439 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
440 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
441 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000442 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000443 // Emit private VarDecl with copy init.
444 EmitDecl(*VD);
445 return GetAddrOfLocalVar(VD);
446 });
447 assert(IsRegistered && "private var already registered as private");
448 // Silence the warning about unused variable.
449 (void)IsRegistered;
450 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000451 ++IRef;
452 }
453 }
454}
455
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000456bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000457 if (!HaveInsertPoint())
458 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000459 // threadprivate_var1 = master_threadprivate_var1;
460 // operator=(threadprivate_var2, master_threadprivate_var2);
461 // ...
462 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000463 llvm::DenseSet<const VarDecl *> CopiedVars;
464 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000465 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000466 auto IRef = C->varlist_begin();
467 auto ISrcRef = C->source_exprs().begin();
468 auto IDestRef = C->destination_exprs().begin();
469 for (auto *AssignOp : C->assignment_ops()) {
470 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000471 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000472 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000473
474 // Get the address of the master variable. If we are emitting code with
475 // TLS support, the address is passed from the master as field in the
476 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000477 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000478 if (getLangOpts().OpenMPUseTLS &&
479 getContext().getTargetInfo().isTLSSupported()) {
480 assert(CapturedStmtInfo->lookup(VD) &&
481 "Copyin threadprivates should have been captured!");
482 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
483 VK_LValue, (*IRef)->getExprLoc());
484 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000485 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000486 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000487 MasterAddr =
488 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
489 : CGM.GetAddrOfGlobal(VD),
490 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000491 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000492 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000493 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000494 if (CopiedVars.size() == 1) {
495 // At first check if current thread is a master thread. If it is, no
496 // need to copy data.
497 CopyBegin = createBasicBlock("copyin.not.master");
498 CopyEnd = createBasicBlock("copyin.not.master.end");
499 Builder.CreateCondBr(
500 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000501 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
502 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000503 CopyBegin, CopyEnd);
504 EmitBlock(CopyBegin);
505 }
506 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
507 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000508 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000509 }
510 ++IRef;
511 ++ISrcRef;
512 ++IDestRef;
513 }
514 }
515 if (CopyEnd) {
516 // Exit out of copying procedure for non-master thread.
517 EmitBlock(CopyEnd, /*IsFinished=*/true);
518 return true;
519 }
520 return false;
521}
522
Alexey Bataev38e89532015-04-16 04:54:05 +0000523bool CodeGenFunction::EmitOMPLastprivateClauseInit(
524 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000525 if (!HaveInsertPoint())
526 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000527 bool HasAtLeastOneLastprivate = false;
528 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000529 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000530 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000531 auto IRef = C->varlist_begin();
532 auto IDestRef = C->destination_exprs().begin();
533 for (auto *IInit : C->private_copies()) {
534 // Keep the address of the original variable for future update at the end
535 // of the loop.
536 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
537 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
538 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000539 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000540 DeclRefExpr DRE(
541 const_cast<VarDecl *>(OrigVD),
542 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
543 OrigVD) != nullptr,
544 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
545 return EmitLValue(&DRE).getAddress();
546 });
547 // Check if the variable is also a firstprivate: in this case IInit is
548 // not generated. Initialization of this variable will happen in codegen
549 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000550 if (IInit) {
551 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
552 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000553 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000554 // Emit private VarDecl with copy init.
555 EmitDecl(*VD);
556 return GetAddrOfLocalVar(VD);
557 });
558 assert(IsRegistered &&
559 "lastprivate var already registered as private");
560 (void)IsRegistered;
561 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000562 }
563 ++IRef, ++IDestRef;
564 }
565 }
566 return HasAtLeastOneLastprivate;
567}
568
569void CodeGenFunction::EmitOMPLastprivateClauseFinal(
570 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000571 if (!HaveInsertPoint())
572 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000573 // Emit following code:
574 // if (<IsLastIterCond>) {
575 // orig_var1 = private_orig_var1;
576 // ...
577 // orig_varn = private_orig_varn;
578 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000579 llvm::BasicBlock *ThenBB = nullptr;
580 llvm::BasicBlock *DoneBB = nullptr;
581 if (IsLastIterCond) {
582 ThenBB = createBasicBlock(".omp.lastprivate.then");
583 DoneBB = createBasicBlock(".omp.lastprivate.done");
584 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
585 EmitBlock(ThenBB);
586 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000587 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
588 const Expr *LastIterVal = nullptr;
589 const Expr *IVExpr = nullptr;
590 const Expr *IncExpr = nullptr;
591 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000592 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
593 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
594 LoopDirective->getUpperBoundVariable())
595 ->getDecl())
596 ->getAnyInitializer();
597 IVExpr = LoopDirective->getIterationVariable();
598 IncExpr = LoopDirective->getInc();
599 auto IUpdate = LoopDirective->updates().begin();
600 for (auto *E : LoopDirective->counters()) {
601 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
602 LoopCountersAndUpdates[D] = *IUpdate;
603 ++IUpdate;
604 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000605 }
606 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000607 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000608 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000609 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000610 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000611 auto IRef = C->varlist_begin();
612 auto ISrcRef = C->source_exprs().begin();
613 auto IDestRef = C->destination_exprs().begin();
614 for (auto *AssignOp : C->assignment_ops()) {
615 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000616 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000617 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
618 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
619 // If lastprivate variable is a loop control variable for loop-based
620 // directive, update its value before copyin back to original
621 // variable.
622 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000623 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000624 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
625 IVExpr->getType().getQualifiers(),
626 /*IsInitializer=*/false);
627 EmitIgnoredExpr(IncExpr);
628 FirstLCV = false;
629 }
630 EmitIgnoredExpr(UpExpr);
631 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000632 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
633 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
634 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000635 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000636 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000637 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
638 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000639 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000640 Address(Builder.CreateLoad(PrivateAddr),
641 getNaturalTypeAlignment(RefTy->getPointeeType()));
642 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000643 }
644 ++IRef;
645 ++ISrcRef;
646 ++IDestRef;
647 }
648 }
649 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000650 if (IsLastIterCond) {
651 EmitBlock(DoneBB, /*IsFinished=*/true);
652 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000653}
654
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000655void CodeGenFunction::EmitOMPReductionClauseInit(
656 const OMPExecutableDirective &D,
657 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000658 if (!HaveInsertPoint())
659 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000660 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000661 auto ILHS = C->lhs_exprs().begin();
662 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000663 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000664 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000665 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000666 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
667 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
668 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
669 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
670 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
671 Base = TempOASE->getBase()->IgnoreParenImpCasts();
672 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
673 Base = TempASE->getBase()->IgnoreParenImpCasts();
674 auto *DE = cast<DeclRefExpr>(Base);
675 auto *OrigVD = cast<VarDecl>(DE->getDecl());
676 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
677 auto OASELValueUB =
678 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
679 auto OriginalBaseLValue = EmitLValue(DE);
680 auto BaseLValue = OriginalBaseLValue;
681 auto *Zero = Builder.getInt64(/*C=*/0);
682 llvm::SmallVector<llvm::Value *, 4> Indexes;
683 Indexes.push_back(Zero);
684 auto *ItemTy =
685 OASELValueLB.getPointer()->getType()->getPointerElementType();
686 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
687 while (Ty != ItemTy) {
688 Indexes.push_back(Zero);
689 Ty = Ty->getPointerElementType();
690 }
691 BaseLValue = MakeAddrLValue(
692 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
693 OASELValueLB.getAlignment()),
694 OASELValueLB.getType(), OASELValueLB.getAlignmentSource());
695 // Store the address of the original variable associated with the LHS
696 // implicit variable.
697 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
698 return OASELValueLB.getAddress();
699 });
700 // Emit reduction copy.
701 bool IsRegistered = PrivateScope.addPrivate(
702 OrigVD, [this, PrivateVD, BaseLValue, OASELValueLB, OASELValueUB,
703 OriginalBaseLValue]() -> Address {
704 // Emit VarDecl with copy init for arrays.
705 // Get the address of the original variable captured in current
706 // captured region.
707 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
708 OASELValueLB.getPointer());
709 Size = Builder.CreateNUWAdd(
710 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
711 CodeGenFunction::OpaqueValueMapping OpaqueMap(
712 *this, cast<OpaqueValueExpr>(
713 getContext()
714 .getAsVariableArrayType(PrivateVD->getType())
715 ->getSizeExpr()),
716 RValue::get(Size));
717 EmitVariablyModifiedType(PrivateVD->getType());
718 auto Emission = EmitAutoVarAlloca(*PrivateVD);
719 auto Addr = Emission.getAllocatedAddress();
720 auto *Init = PrivateVD->getInit();
721 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
722 EmitAutoVarCleanups(Emission);
723 // Emit private VarDecl with reduction init.
724 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
725 OASELValueLB.getPointer());
726 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
727 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
728 Ptr, OriginalBaseLValue.getPointer()->getType());
729 return Address(Ptr, OriginalBaseLValue.getAlignment());
730 });
731 assert(IsRegistered && "private var already registered as private");
732 // Silence the warning about unused variable.
733 (void)IsRegistered;
734 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
735 return GetAddrOfLocalVar(PrivateVD);
736 });
737 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
738 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
739 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
740 Base = TempASE->getBase()->IgnoreParenImpCasts();
741 auto *DE = cast<DeclRefExpr>(Base);
742 auto *OrigVD = cast<VarDecl>(DE->getDecl());
743 auto ASELValue = EmitLValue(ASE);
744 auto OriginalBaseLValue = EmitLValue(DE);
745 auto BaseLValue = OriginalBaseLValue;
746 auto *Zero = Builder.getInt64(/*C=*/0);
747 llvm::SmallVector<llvm::Value *, 4> Indexes;
748 Indexes.push_back(Zero);
749 auto *ItemTy =
750 ASELValue.getPointer()->getType()->getPointerElementType();
751 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
752 while (Ty != ItemTy) {
753 Indexes.push_back(Zero);
754 Ty = Ty->getPointerElementType();
755 }
756 BaseLValue = MakeAddrLValue(
757 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
758 ASELValue.getAlignment()),
759 ASELValue.getType(), ASELValue.getAlignmentSource());
760 // Store the address of the original variable associated with the LHS
761 // implicit variable.
762 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
763 return ASELValue.getAddress();
764 });
765 // Emit reduction copy.
766 bool IsRegistered = PrivateScope.addPrivate(
767 OrigVD, [this, PrivateVD, BaseLValue, ASELValue,
768 OriginalBaseLValue]() -> Address {
769 // Emit private VarDecl with reduction init.
770 EmitDecl(*PrivateVD);
771 auto Addr = GetAddrOfLocalVar(PrivateVD);
772 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
773 ASELValue.getPointer());
774 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
775 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
776 Ptr, OriginalBaseLValue.getPointer()->getType());
777 return Address(Ptr, OriginalBaseLValue.getAlignment());
778 });
779 assert(IsRegistered && "private var already registered as private");
780 // Silence the warning about unused variable.
781 (void)IsRegistered;
782 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
783 return GetAddrOfLocalVar(PrivateVD);
784 });
785 } else {
786 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
787 // Store the address of the original variable associated with the LHS
788 // implicit variable.
789 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
790 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
791 CapturedStmtInfo->lookup(OrigVD) != nullptr,
792 IRef->getType(), VK_LValue, IRef->getExprLoc());
793 return EmitLValue(&DRE).getAddress();
794 });
795 // Emit reduction copy.
796 bool IsRegistered =
797 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
798 // Emit private VarDecl with reduction init.
799 EmitDecl(*PrivateVD);
800 return GetAddrOfLocalVar(PrivateVD);
801 });
802 assert(IsRegistered && "private var already registered as private");
803 // Silence the warning about unused variable.
804 (void)IsRegistered;
805 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
806 return GetAddrOfLocalVar(PrivateVD);
807 });
808 }
809 ++ILHS, ++IRHS, ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000810 }
811 }
812}
813
814void CodeGenFunction::EmitOMPReductionClauseFinal(
815 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000816 if (!HaveInsertPoint())
817 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000818 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000819 llvm::SmallVector<const Expr *, 8> LHSExprs;
820 llvm::SmallVector<const Expr *, 8> RHSExprs;
821 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000822 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000823 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000824 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000825 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000826 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
827 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
828 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
829 }
830 if (HasAtLeastOneReduction) {
831 // Emit nowait reduction if nowait clause is present or directive is a
832 // parallel directive (it always has implicit barrier).
833 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000834 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000835 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000836 isOpenMPParallelDirective(D.getDirectiveKind()) ||
837 D.getDirectiveKind() == OMPD_simd,
838 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000839 }
840}
841
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000842static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
843 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000844 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000845 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000846 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000847 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
848 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000849 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000850 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000851 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000852 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000853 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
854 /*IgnoreResultAssign*/ true);
855 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
856 CGF, NumThreads, NumThreadsClause->getLocStart());
857 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000858 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000859 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000860 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
861 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
862 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000863 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000864 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
865 if (C->getNameModifier() == OMPD_unknown ||
866 C->getNameModifier() == OMPD_parallel) {
867 IfCond = C->getCondition();
868 break;
869 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000870 }
871 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000872 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000873}
874
875void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
876 LexicalScope Scope(*this, S.getSourceRange());
877 // Emit parallel region as a standalone region.
878 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
879 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000880 bool Copyins = CGF.EmitOMPCopyinClause(S);
881 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
882 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000883 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000884 // initialization of firstprivate variables or propagation master's thread
885 // values of threadprivate variables to local instances of that variables
886 // of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000887 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
888 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
889 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000890 }
891 CGF.EmitOMPPrivateClause(S, PrivateScope);
892 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
893 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000894 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000895 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000896 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000897 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000898}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000899
Alexey Bataev0f34da12015-07-02 04:17:07 +0000900void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
901 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000902 RunCleanupsScope BodyScope(*this);
903 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000904 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000905 EmitIgnoredExpr(I);
906 }
Alexander Musman3276a272015-03-21 10:12:56 +0000907 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000908 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000909 for (auto U : C->updates()) {
910 EmitIgnoredExpr(U);
911 }
912 }
913
Alexander Musmana5f070a2014-10-01 06:03:56 +0000914 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000915 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000916 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000917 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000918 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000919 // The end (updates/cleanups).
920 EmitBlock(Continue.getBlock());
921 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000922 // TODO: Update lastprivates if the SeparateIter flag is true.
923 // This will be implemented in a follow-up OMPLastprivateClause patch, but
924 // result should be still correct without it, as we do not make these
925 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000926}
927
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000928void CodeGenFunction::EmitOMPInnerLoop(
929 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
930 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000931 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
932 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000933 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000934
935 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000936 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000937 EmitBlock(CondBlock);
938 LoopStack.push(CondBlock);
939
940 // If there are any cleanups between here and the loop-exit scope,
941 // create a block to stage a loop exit along.
942 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000943 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000944 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000945
Alexander Musmand196ef22014-10-07 08:57:09 +0000946 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000947
Alexey Bataev2df54a02015-03-12 08:53:29 +0000948 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000949 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000950 if (ExitBlock != LoopExit.getBlock()) {
951 EmitBlock(ExitBlock);
952 EmitBranchThroughCleanup(LoopExit);
953 }
954
955 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000956 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000957
958 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000959 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000960 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
961
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000962 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000963
964 // Emit "IV = IV + 1" and a back-edge to the condition block.
965 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000966 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000967 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000968 BreakContinueStack.pop_back();
969 EmitBranch(CondBlock);
970 LoopStack.pop();
971 // Emit the fall-through block.
972 EmitBlock(LoopExit.getBlock());
973}
974
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000975void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000976 if (!HaveInsertPoint())
977 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000978 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000979 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000980 for (auto Init : C->inits()) {
981 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000982 auto *OrigVD = cast<VarDecl>(
983 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
984 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
985 CapturedStmtInfo->lookup(OrigVD) != nullptr,
986 VD->getInit()->getType(), VK_LValue,
987 VD->getInit()->getExprLoc());
988 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
989 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +0000990 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000991 /*capturedByInit=*/false);
992 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000993 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000994 // Emit the linear steps for the linear clauses.
995 // If a step is not constant, it is pre-calculated before the loop.
996 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
997 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000998 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000999 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001000 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001001 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001002 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001003}
1004
1005static void emitLinearClauseFinal(CodeGenFunction &CGF,
1006 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001007 if (!CGF.HaveInsertPoint())
1008 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001009 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001010 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001011 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001012 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001013 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1014 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001015 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001016 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001017 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001018 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001019 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001020 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001021 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001022 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001023 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001024 }
1025 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001026}
1027
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001028static void emitAlignedClause(CodeGenFunction &CGF,
1029 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001030 if (!CGF.HaveInsertPoint())
1031 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001032 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001033 unsigned ClauseAlignment = 0;
1034 if (auto AlignmentExpr = Clause->getAlignment()) {
1035 auto AlignmentCI =
1036 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1037 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001038 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001039 for (auto E : Clause->varlists()) {
1040 unsigned Alignment = ClauseAlignment;
1041 if (Alignment == 0) {
1042 // OpenMP [2.8.1, Description]
1043 // If no optional parameter is specified, implementation-defined default
1044 // alignments for SIMD instructions on the target platforms are assumed.
1045 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001046 CGF.getContext()
1047 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1048 E->getType()->getPointeeType()))
1049 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001050 }
1051 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1052 "alignment is not power of 2");
1053 if (Alignment != 0) {
1054 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1055 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1056 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001057 }
1058 }
1059}
1060
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001061static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001062 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001063 ArrayRef<Expr *> Counters,
1064 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001065 if (!CGF.HaveInsertPoint())
1066 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001067 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001068 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001069 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1070 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001071 Address Addr = Address::invalid();
1072 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001073 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001074 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001075 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001076 Addr = VarEmission.getAllocatedAddress();
1077 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001078 });
John McCall7f416cc2015-09-08 08:05:57 +00001079 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001080 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001081 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001082}
1083
Alexey Bataev62dbb972015-04-22 11:59:37 +00001084static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1085 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1086 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001087 if (!CGF.HaveInsertPoint())
1088 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001089 {
1090 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001091 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1092 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001093 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001094 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001095 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001096 CGF.EmitIgnoredExpr(I);
1097 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001098 }
1099 // Check that loop is executed at least one time.
1100 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1101}
1102
Alexander Musman3276a272015-03-21 10:12:56 +00001103static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001104emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001105 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001106 if (!CGF.HaveInsertPoint())
1107 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001108 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001109 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001110 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001111 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1112 auto *PrivateVD =
1113 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001114 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001115 // Emit private VarDecl with copy init.
1116 CGF.EmitVarDecl(*PrivateVD);
1117 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001118 });
1119 assert(IsRegistered && "linear var already registered as private");
1120 // Silence the warning about unused variable.
1121 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001122 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001123 }
1124 }
1125}
1126
Alexey Bataev45bfad52015-08-21 12:19:04 +00001127static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001128 const OMPExecutableDirective &D,
1129 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001130 if (!CGF.HaveInsertPoint())
1131 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001132 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001133 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1134 /*ignoreResult=*/true);
1135 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1136 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1137 // In presence of finite 'safelen', it may be unsafe to mark all
1138 // the memory instructions parallel, because loop-carried
1139 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001140 if (!IsMonotonic)
1141 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001142 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001143 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1144 /*ignoreResult=*/true);
1145 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001146 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001147 // In presence of finite 'safelen', it may be unsafe to mark all
1148 // the memory instructions parallel, because loop-carried
1149 // dependences of 'safelen' iterations are possible.
1150 CGF.LoopStack.setParallel(false);
1151 }
1152}
1153
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001154void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1155 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001156 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001157 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001158 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001159 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001160}
1161
1162void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001163 if (!HaveInsertPoint())
1164 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001165 auto IC = D.counters().begin();
1166 for (auto F : D.finals()) {
1167 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001168 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001169 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1170 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1171 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001172 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001173 OMPPrivateScope VarScope(*this);
1174 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001175 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001176 (void)VarScope.Privatize();
1177 EmitIgnoredExpr(F);
1178 }
1179 ++IC;
1180 }
1181 emitLinearClauseFinal(*this, D);
1182}
1183
Alexander Musman515ad8c2014-05-22 08:54:05 +00001184void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001185 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001186 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001187 // for (IV in 0..LastIteration) BODY;
1188 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001189 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001190 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001191
Alexey Bataev62dbb972015-04-22 11:59:37 +00001192 // Emit: if (PreCond) - begin.
1193 // If the condition constant folds and can be elided, avoid emitting the
1194 // whole loop.
1195 bool CondConstant;
1196 llvm::BasicBlock *ContBlock = nullptr;
1197 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1198 if (!CondConstant)
1199 return;
1200 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001201 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1202 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001203 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1204 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001205 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001206 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001207 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001208
1209 // Emit the loop iteration variable.
1210 const Expr *IVExpr = S.getIterationVariable();
1211 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1212 CGF.EmitVarDecl(*IVDecl);
1213 CGF.EmitIgnoredExpr(S.getInit());
1214
1215 // Emit the iterations count variable.
1216 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001217 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001218 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1219 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1220 // Emit calculation of the iterations count.
1221 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001222 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001223
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001224 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001225
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001226 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001227 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001228 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001229 {
1230 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001231 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1232 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001233 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001234 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001235 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001236 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001237 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001238 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1239 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001240 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001241 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001242 CGF.EmitStopPoint(&S);
1243 },
1244 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001245 // Emit final copy of the lastprivate variables at the end of loops.
1246 if (HasLastprivateClause) {
1247 CGF.EmitOMPLastprivateClauseFinal(S);
1248 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001249 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001250 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001251 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001252 // Emit: if (PreCond) - end.
1253 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001254 CGF.EmitBranch(ContBlock);
1255 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001256 }
1257 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001258 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001259}
1260
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001261void CodeGenFunction::EmitOMPForOuterLoop(
1262 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1263 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1264 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001265 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001266
1267 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001268 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001269
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001270 assert((Ordered ||
1271 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001272 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001273
1274 // Emit outer loop.
1275 //
1276 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001277 // When schedule(dynamic,chunk_size) is specified, the iterations are
1278 // distributed to threads in the team in chunks as the threads request them.
1279 // Each thread executes a chunk of iterations, then requests another chunk,
1280 // until no chunks remain to be distributed. Each chunk contains chunk_size
1281 // iterations, except for the last chunk to be distributed, which may have
1282 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1283 //
1284 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1285 // to threads in the team in chunks as the executing threads request them.
1286 // Each thread executes a chunk of iterations, then requests another chunk,
1287 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1288 // each chunk is proportional to the number of unassigned iterations divided
1289 // by the number of threads in the team, decreasing to 1. For a chunk_size
1290 // with value k (greater than 1), the size of each chunk is determined in the
1291 // same way, with the restriction that the chunks do not contain fewer than k
1292 // iterations (except for the last chunk to be assigned, which may have fewer
1293 // than k iterations).
1294 //
1295 // When schedule(auto) is specified, the decision regarding scheduling is
1296 // delegated to the compiler and/or runtime system. The programmer gives the
1297 // implementation the freedom to choose any possible mapping of iterations to
1298 // threads in the team.
1299 //
1300 // When schedule(runtime) is specified, the decision regarding scheduling is
1301 // deferred until run time, and the schedule and chunk size are taken from the
1302 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1303 // implementation defined
1304 //
1305 // while(__kmpc_dispatch_next(&LB, &UB)) {
1306 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001307 // while (idx <= UB) { BODY; ++idx;
1308 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1309 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001310 // }
1311 //
1312 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001313 // When schedule(static, chunk_size) is specified, iterations are divided into
1314 // chunks of size chunk_size, and the chunks are assigned to the threads in
1315 // the team in a round-robin fashion in the order of the thread number.
1316 //
1317 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1318 // while (idx <= UB) { BODY; ++idx; } // inner loop
1319 // LB = LB + ST;
1320 // UB = UB + ST;
1321 // }
1322 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001323
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001324 const Expr *IVExpr = S.getIterationVariable();
1325 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1326 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1327
John McCall7f416cc2015-09-08 08:05:57 +00001328 if (DynamicOrOrdered) {
1329 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1330 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1331 IVSize, IVSigned, Ordered, UBVal, Chunk);
1332 } else {
1333 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1334 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1335 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001336
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001337 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1338
1339 // Start the loop with a block that tests the condition.
1340 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1341 EmitBlock(CondBlock);
1342 LoopStack.push(CondBlock);
1343
1344 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001345 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001346 // UB = min(UB, GlobalUB)
1347 EmitIgnoredExpr(S.getEnsureUpperBound());
1348 // IV = LB
1349 EmitIgnoredExpr(S.getInit());
1350 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001351 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001352 } else {
1353 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1354 IL, LB, UB, ST);
1355 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001356
1357 // If there are any cleanups between here and the loop-exit scope,
1358 // create a block to stage a loop exit along.
1359 auto ExitBlock = LoopExit.getBlock();
1360 if (LoopScope.requiresCleanups())
1361 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1362
1363 auto LoopBody = createBasicBlock("omp.dispatch.body");
1364 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1365 if (ExitBlock != LoopExit.getBlock()) {
1366 EmitBlock(ExitBlock);
1367 EmitBranchThroughCleanup(LoopExit);
1368 }
1369 EmitBlock(LoopBody);
1370
Alexander Musman92bdaab2015-03-12 13:37:50 +00001371 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1372 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001373 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001374 EmitIgnoredExpr(S.getInit());
1375
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001376 // Create a block for the increment.
1377 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1378 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1379
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001380 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1381 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001382 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1383 LoopStack.setParallel(!IsMonotonic);
1384 else
1385 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001386
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001387 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001388 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1389 [&S, LoopExit](CodeGenFunction &CGF) {
1390 CGF.EmitOMPLoopBody(S, LoopExit);
1391 CGF.EmitStopPoint(&S);
1392 },
1393 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1394 if (Ordered) {
1395 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1396 CGF, Loc, IVSize, IVSigned);
1397 }
1398 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001399
1400 EmitBlock(Continue.getBlock());
1401 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001402 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001403 // Emit "LB = LB + Stride", "UB = UB + Stride".
1404 EmitIgnoredExpr(S.getNextLowerBound());
1405 EmitIgnoredExpr(S.getNextUpperBound());
1406 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001407
1408 EmitBranch(CondBlock);
1409 LoopStack.pop();
1410 // Emit the fall-through block.
1411 EmitBlock(LoopExit.getBlock());
1412
1413 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001414 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001415 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001416}
1417
Alexander Musmanc6388682014-12-15 07:07:06 +00001418/// \brief Emit a helper variable and return corresponding lvalue.
1419static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1420 const DeclRefExpr *Helper) {
1421 auto VDecl = cast<VarDecl>(Helper->getDecl());
1422 CGF.EmitVarDecl(*VDecl);
1423 return CGF.EmitLValue(Helper);
1424}
1425
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001426namespace {
1427 struct ScheduleKindModifiersTy {
1428 OpenMPScheduleClauseKind Kind;
1429 OpenMPScheduleClauseModifier M1;
1430 OpenMPScheduleClauseModifier M2;
1431 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1432 OpenMPScheduleClauseModifier M1,
1433 OpenMPScheduleClauseModifier M2)
1434 : Kind(Kind), M1(M1), M2(M2) {}
1435 };
1436} // namespace
1437
1438static std::pair<llvm::Value * /*Chunk*/, ScheduleKindModifiersTy>
Alexey Bataev040d5402015-05-12 08:35:28 +00001439emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1440 bool OuterRegion) {
1441 // Detect the loop schedule kind and chunk.
1442 auto ScheduleKind = OMPC_SCHEDULE_unknown;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001443 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1444 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
Alexey Bataev040d5402015-05-12 08:35:28 +00001445 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001446 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001447 ScheduleKind = C->getScheduleKind();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001448 M1 = C->getFirstScheduleModifier();
1449 M2 = C->getSecondScheduleModifier();
Alexey Bataev040d5402015-05-12 08:35:28 +00001450 if (const auto *Ch = C->getChunkSize()) {
1451 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1452 if (OuterRegion) {
1453 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1454 CGF.EmitVarDecl(*ImpVar);
1455 CGF.EmitStoreThroughLValue(
1456 CGF.EmitAnyExpr(Ch),
John McCall7f416cc2015-09-08 08:05:57 +00001457 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1458 ImpVar->getType()));
Alexey Bataev040d5402015-05-12 08:35:28 +00001459 } else {
1460 Ch = ImpRef;
1461 }
1462 }
1463 if (!C->getHelperChunkSize() || !OuterRegion) {
1464 Chunk = CGF.EmitScalarExpr(Ch);
1465 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001466 S.getIterationVariable()->getType(),
1467 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001468 }
1469 }
1470 }
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001471 return std::make_pair(Chunk, ScheduleKindModifiersTy(ScheduleKind, M1, M2));
Alexey Bataev040d5402015-05-12 08:35:28 +00001472}
1473
Alexey Bataev38e89532015-04-16 04:54:05 +00001474bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001475 // Emit the loop iteration variable.
1476 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1477 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1478 EmitVarDecl(*IVDecl);
1479
1480 // Emit the iterations count variable.
1481 // If it is not a variable, Sema decided to calculate iterations count on each
1482 // iteration (e.g., it is foldable into a constant).
1483 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1484 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1485 // Emit calculation of the iterations count.
1486 EmitIgnoredExpr(S.getCalcLastIteration());
1487 }
1488
1489 auto &RT = CGM.getOpenMPRuntime();
1490
Alexey Bataev38e89532015-04-16 04:54:05 +00001491 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001492 // Check pre-condition.
1493 {
1494 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001495 // If the condition constant folds and can be elided, avoid emitting the
1496 // whole loop.
1497 bool CondConstant;
1498 llvm::BasicBlock *ContBlock = nullptr;
1499 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1500 if (!CondConstant)
1501 return false;
1502 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001503 auto *ThenBlock = createBasicBlock("omp.precond.then");
1504 ContBlock = createBasicBlock("omp.precond.end");
1505 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001506 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001507 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001508 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001509 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001510
1511 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001512 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001513 // Emit 'then' code.
1514 {
1515 // Emit helper vars inits.
1516 LValue LB =
1517 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1518 LValue UB =
1519 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1520 LValue ST =
1521 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1522 LValue IL =
1523 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1524
1525 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001526 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1527 // Emit implicit barrier to synchronize threads and avoid data races on
1528 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001529 CGM.getOpenMPRuntime().emitBarrierCall(
1530 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1531 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001532 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001533 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001534 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001535 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001536 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1537 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001538 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001539 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001540
1541 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001542 llvm::Value *Chunk;
1543 OpenMPScheduleClauseKind ScheduleKind;
1544 auto ScheduleInfo =
1545 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1546 Chunk = ScheduleInfo.first;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001547 ScheduleKind = ScheduleInfo.second.Kind;
1548 const OpenMPScheduleClauseModifier M1 = ScheduleInfo.second.M1;
1549 const OpenMPScheduleClauseModifier M2 = ScheduleInfo.second.M2;
Alexander Musmanc6388682014-12-15 07:07:06 +00001550 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1551 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001552 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001553 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1554 // If the static schedule kind is specified or if the ordered clause is
1555 // specified, and if no monotonic modifier is specified, the effect will
1556 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001557 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001558 /* Chunked */ Chunk != nullptr) &&
1559 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001560 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1561 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001562 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1563 // When no chunk_size is specified, the iteration space is divided into
1564 // chunks that are approximately equal in size, and at most one chunk is
1565 // distributed to each thread. Note that the size of the chunks is
1566 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001567 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1568 IVSize, IVSigned, Ordered,
1569 IL.getAddress(), LB.getAddress(),
1570 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001571 auto LoopExit =
1572 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001573 // UB = min(UB, GlobalUB);
1574 EmitIgnoredExpr(S.getEnsureUpperBound());
1575 // IV = LB;
1576 EmitIgnoredExpr(S.getInit());
1577 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001578 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1579 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001580 [&S, LoopExit](CodeGenFunction &CGF) {
1581 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001582 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001583 },
1584 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001585 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001586 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001587 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001588 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001589 const bool IsMonotonic = Ordered ||
1590 ScheduleKind == OMPC_SCHEDULE_static ||
1591 ScheduleKind == OMPC_SCHEDULE_unknown ||
1592 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1593 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001594 // Emit the outer loop, which requests its work chunk [LB..UB] from
1595 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001596 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001597 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1598 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001599 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001600 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001601 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1602 if (HasLastprivateClause)
1603 EmitOMPLastprivateClauseFinal(
1604 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001605 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001606 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1607 EmitOMPSimdFinal(S);
1608 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001609 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001610 if (ContBlock) {
1611 EmitBranch(ContBlock);
1612 EmitBlock(ContBlock, true);
1613 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001614 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001615 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001616}
1617
1618void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001619 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001620 bool HasLastprivates = false;
1621 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1622 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1623 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001624 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1625 S.hasCancel());
Alexander Musmanc6388682014-12-15 07:07:06 +00001626
1627 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001628 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001629 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1630 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001631}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001632
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001633void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1634 LexicalScope Scope(*this, S.getSourceRange());
1635 bool HasLastprivates = false;
1636 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1637 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1638 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001639 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001640
1641 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001642 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001643 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1644 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001645}
1646
Alexey Bataev2df54a02015-03-12 08:53:29 +00001647static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1648 const Twine &Name,
1649 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001650 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001651 if (Init)
1652 CGF.EmitScalarInit(Init, LVal);
1653 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001654}
1655
Alexey Bataev0f34da12015-07-02 04:17:07 +00001656OpenMPDirectiveKind
1657CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001658 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1659 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1660 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001661 bool HasLastprivates = false;
1662 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001663 auto &C = CGF.CGM.getContext();
1664 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1665 // Emit helper vars inits.
1666 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1667 CGF.Builder.getInt32(0));
1668 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1669 LValue UB =
1670 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1671 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1672 CGF.Builder.getInt32(1));
1673 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1674 CGF.Builder.getInt32(0));
1675 // Loop counter.
1676 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1677 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001678 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001679 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001680 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001681 // Generate condition for loop.
1682 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1683 OK_Ordinary, S.getLocStart(),
1684 /*fpContractable=*/false);
1685 // Increment for loop counter.
1686 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1687 OK_Ordinary, S.getLocStart());
1688 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1689 // Iterate through all sections and emit a switch construct:
1690 // switch (IV) {
1691 // case 0:
1692 // <SectionStmt[0]>;
1693 // break;
1694 // ...
1695 // case <NumSection> - 1:
1696 // <SectionStmt[<NumSection> - 1]>;
1697 // break;
1698 // }
1699 // .omp.sections.exit:
1700 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1701 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1702 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1703 CS->size());
1704 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001705 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001706 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1707 CGF.EmitBlock(CaseBB);
1708 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001709 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001710 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001711 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001712 }
1713 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1714 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001715
1716 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1717 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1718 // Emit implicit barrier to synchronize threads and avoid data races on
1719 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001720 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1721 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1722 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001723 }
Alexey Bataev73870832015-04-27 04:12:12 +00001724 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001725 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001726 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001727 (void)LoopScope.Privatize();
1728
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001729 // Emit static non-chunked loop.
John McCall7f416cc2015-09-08 08:05:57 +00001730 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001731 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001732 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1733 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001734 // UB = min(UB, GlobalUB);
1735 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1736 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1737 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1738 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1739 // IV = LB;
1740 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1741 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001742 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1743 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001744 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001745 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001746 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001747
1748 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1749 if (HasLastprivates)
1750 CGF.EmitOMPLastprivateClauseFinal(
1751 S, CGF.Builder.CreateIsNotNull(
1752 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001753 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001754
Alexey Bataev25e5b442015-09-15 12:52:43 +00001755 bool HasCancel = false;
1756 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1757 HasCancel = OSD->hasCancel();
1758 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1759 HasCancel = OPSD->hasCancel();
1760 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1761 HasCancel);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001762 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1763 // clause. Otherwise the barrier will be generated by the codegen for the
1764 // directive.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001765 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001766 // Emit implicit barrier to synchronize threads and avoid data races on
1767 // initialization of firstprivate variables.
Alexey Bataev0f34da12015-07-02 04:17:07 +00001768 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1769 OMPD_unknown);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001770 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001771 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001772 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001773 // If only one section is found - no need to generate loop, emit as a single
1774 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001775 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001776 // No need to generate reductions for sections with single section region, we
1777 // can use original shared variables for all operations.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001778 bool HasReductions = S.hasClausesOfKind<OMPReductionClause>();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001779 // No need to generate lastprivates for sections with single section region,
1780 // we can use original shared variable for all calculations with barrier at
1781 // the end of the sections.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001782 bool HasLastprivates = S.hasClausesOfKind<OMPLastprivateClause>();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001783 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1784 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1785 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001786 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001787 (void)SingleScope.Privatize();
1788
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001789 CGF.EmitStmt(Stmt);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001790 };
Alexey Bataev0f34da12015-07-02 04:17:07 +00001791 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1792 llvm::None, llvm::None, llvm::None,
1793 llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001794 // Emit barrier for firstprivates, lastprivates or reductions only if
1795 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1796 // generated by the codegen for the directive.
1797 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001798 S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001799 // Emit implicit barrier to synchronize threads and avoid data races on
1800 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001801 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown,
1802 /*EmitChecks=*/false,
1803 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001804 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001805 return OMPD_single;
1806}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001807
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001808void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1809 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001810 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001811 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001812 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001813 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001814 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001815}
1816
1817void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001818 LexicalScope Scope(*this, S.getSourceRange());
1819 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1820 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001821 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001822 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1823 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001824}
1825
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001826void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001827 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001828 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001829 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001830 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001831 // Check if there are any 'copyprivate' clauses associated with this
1832 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001833 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001834 // Build a list of copyprivate variables along with helper expressions
1835 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001836 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001837 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001838 DestExprs.append(C->destination_exprs().begin(),
1839 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001840 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001841 AssignmentOps.append(C->assignment_ops().begin(),
1842 C->assignment_ops().end());
1843 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001844 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001845 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001846 bool HasFirstprivates;
1847 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1848 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1849 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001850 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001851 (void)SingleScope.Privatize();
1852
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001853 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001854 };
1855 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001856 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001857 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001858 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1859 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001860 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001861 CopyprivateVars.empty()) {
1862 CGM.getOpenMPRuntime().emitBarrierCall(
1863 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001864 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001865 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001866}
1867
Alexey Bataev8d690652014-12-04 07:23:53 +00001868void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001869 LexicalScope Scope(*this, S.getSourceRange());
1870 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1871 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001872 };
1873 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001874}
1875
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001876void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001877 LexicalScope Scope(*this, S.getSourceRange());
1878 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1879 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001880 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001881 Expr *Hint = nullptr;
1882 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1883 Hint = HintClause->getHint();
1884 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1885 S.getDirectiveName().getAsString(),
1886 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001887}
1888
Alexey Bataev671605e2015-04-13 05:28:11 +00001889void CodeGenFunction::EmitOMPParallelForDirective(
1890 const OMPParallelForDirective &S) {
1891 // Emit directive as a combined directive that consists of two implicit
1892 // directives: 'parallel' with 'for' directive.
1893 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001894 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001895 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1896 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001897 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001898 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001899}
1900
Alexander Musmane4e893b2014-09-23 09:33:00 +00001901void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001902 const OMPParallelForSimdDirective &S) {
1903 // Emit directive as a combined directive that consists of two implicit
1904 // directives: 'parallel' with 'for' directive.
1905 LexicalScope Scope(*this, S.getSourceRange());
1906 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1907 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1908 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001909 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001910 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001911}
1912
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001913void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001914 const OMPParallelSectionsDirective &S) {
1915 // Emit directive as a combined directive that consists of two implicit
1916 // directives: 'parallel' with 'sections' directive.
1917 LexicalScope Scope(*this, S.getSourceRange());
1918 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001919 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001920 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001921 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001922}
1923
Alexey Bataev62b63b12015-03-10 07:28:44 +00001924void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1925 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001926 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001927 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1928 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1929 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001930 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001931 // The first function argument for tasks is a thread id, the second one is a
1932 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001933 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1934 // Get list of private variables.
1935 llvm::SmallVector<const Expr *, 8> PrivateVars;
1936 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001937 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001938 auto IRef = C->varlist_begin();
1939 for (auto *IInit : C->private_copies()) {
1940 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1941 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1942 PrivateVars.push_back(*IRef);
1943 PrivateCopies.push_back(IInit);
1944 }
1945 ++IRef;
1946 }
1947 }
1948 EmittedAsPrivate.clear();
1949 // Get list of firstprivate variables.
1950 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1951 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1952 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001953 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001954 auto IRef = C->varlist_begin();
1955 auto IElemInitRef = C->inits().begin();
1956 for (auto *IInit : C->private_copies()) {
1957 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1958 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1959 FirstprivateVars.push_back(*IRef);
1960 FirstprivateCopies.push_back(IInit);
1961 FirstprivateInits.push_back(*IElemInitRef);
1962 }
1963 ++IRef, ++IElemInitRef;
1964 }
1965 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001966 // Build list of dependences.
1967 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1968 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001969 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001970 for (auto *IRef : C->varlists()) {
1971 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1972 }
1973 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001974 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1975 CodeGenFunction &CGF) {
1976 // Set proper addresses for generated private copies.
1977 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1978 OMPPrivateScope Scope(CGF);
1979 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00001980 auto *CopyFn = CGF.Builder.CreateLoad(
1981 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
1982 auto *PrivatesPtr = CGF.Builder.CreateLoad(
1983 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001984 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00001985 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001986 PrivatePtrs;
1987 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1988 CallArgs.push_back(PrivatesPtr);
1989 for (auto *E : PrivateVars) {
1990 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001991 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001992 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1993 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001994 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001995 }
1996 for (auto *E : FirstprivateVars) {
1997 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001998 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001999 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2000 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002001 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002002 }
2003 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2004 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002005 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2006 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002007 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2008 }
2009 }
2010 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002011 if (*PartId) {
2012 // TODO: emit code for untied tasks.
2013 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002014 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002015 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002016 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2017 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002018 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002019 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002020 // Check if the task is final
2021 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002022 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002023 // If the condition constant folds and can be elided, try to avoid emitting
2024 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002025 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002026 bool CondConstant;
2027 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2028 Final.setInt(CondConstant);
2029 else
2030 Final.setPointer(EvaluateExprAsBool(Cond));
2031 } else {
2032 // By default the task is not final.
2033 Final.setInt(/*IntVal=*/false);
2034 }
2035 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002036 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002037 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2038 if (C->getNameModifier() == OMPD_unknown ||
2039 C->getNameModifier() == OMPD_task) {
2040 IfCond = C->getCondition();
2041 break;
2042 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002043 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002044 CGM.getOpenMPRuntime().emitTaskCall(
2045 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002046 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002047 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002048}
2049
Alexey Bataev9f797f32015-02-05 05:57:51 +00002050void CodeGenFunction::EmitOMPTaskyieldDirective(
2051 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002052 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002053}
2054
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002055void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002056 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002057}
2058
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002059void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2060 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002061}
2062
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002063void CodeGenFunction::EmitOMPTaskgroupDirective(
2064 const OMPTaskgroupDirective &S) {
2065 LexicalScope Scope(*this, S.getSourceRange());
2066 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2067 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002068 };
2069 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2070}
2071
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002072void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002073 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002074 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002075 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2076 FlushClause->varlist_end());
2077 }
2078 return llvm::None;
2079 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002080}
2081
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002082void CodeGenFunction::EmitOMPDistributeDirective(
2083 const OMPDistributeDirective &S) {
2084 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2085}
2086
Alexey Bataev5f600d62015-09-29 03:48:57 +00002087static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2088 const CapturedStmt *S) {
2089 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2090 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2091 CGF.CapturedStmtInfo = &CapStmtInfo;
2092 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2093 Fn->addFnAttr(llvm::Attribute::NoInline);
2094 return Fn;
2095}
2096
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002097void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002098 if (!S.getAssociatedStmt())
2099 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002100 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev5f600d62015-09-29 03:48:57 +00002101 auto *C = S.getSingleClause<OMPSIMDClause>();
2102 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2103 if (C) {
2104 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2105 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2106 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2107 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2108 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2109 } else {
2110 CGF.EmitStmt(
2111 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2112 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002113 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002114 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002115}
2116
Alexey Bataevb57056f2015-01-22 06:17:56 +00002117static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002118 QualType SrcType, QualType DestType,
2119 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002120 assert(CGF.hasScalarEvaluationKind(DestType) &&
2121 "DestType must have scalar evaluation kind.");
2122 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2123 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002124 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2125 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002126 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002127 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002128}
2129
2130static CodeGenFunction::ComplexPairTy
2131convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002132 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002133 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2134 "DestType must have complex evaluation kind.");
2135 CodeGenFunction::ComplexPairTy ComplexVal;
2136 if (Val.isScalar()) {
2137 // Convert the input element to the element type of the complex.
2138 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002139 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2140 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002141 ComplexVal = CodeGenFunction::ComplexPairTy(
2142 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2143 } else {
2144 assert(Val.isComplex() && "Must be a scalar or complex.");
2145 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2146 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2147 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002148 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002149 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002150 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002151 }
2152 return ComplexVal;
2153}
2154
Alexey Bataev5e018f92015-04-23 06:35:10 +00002155static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2156 LValue LVal, RValue RVal) {
2157 if (LVal.isGlobalReg()) {
2158 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2159 } else {
2160 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2161 : llvm::Monotonic,
2162 LVal.isVolatile(), /*IsInit=*/false);
2163 }
2164}
2165
2166static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002167 QualType RValTy, SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002168 switch (CGF.getEvaluationKind(LVal.getType())) {
2169 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002170 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2171 CGF, RVal, RValTy, LVal.getType(), Loc)),
2172 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002173 break;
2174 case TEK_Complex:
2175 CGF.EmitStoreOfComplex(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002176 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002177 /*isInit=*/false);
2178 break;
2179 case TEK_Aggregate:
2180 llvm_unreachable("Must be a scalar or complex.");
2181 }
2182}
2183
Alexey Bataevb57056f2015-01-22 06:17:56 +00002184static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2185 const Expr *X, const Expr *V,
2186 SourceLocation Loc) {
2187 // v = x;
2188 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2189 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2190 LValue XLValue = CGF.EmitLValue(X);
2191 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002192 RValue Res = XLValue.isGlobalReg()
2193 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2194 : CGF.EmitAtomicLoad(XLValue, Loc,
2195 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002196 : llvm::Monotonic,
2197 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002198 // OpenMP, 2.12.6, atomic Construct
2199 // Any atomic construct with a seq_cst clause forces the atomically
2200 // performed operation to include an implicit flush operation without a
2201 // list.
2202 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002203 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002204 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002205}
2206
Alexey Bataevb8329262015-02-27 06:33:30 +00002207static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2208 const Expr *X, const Expr *E,
2209 SourceLocation Loc) {
2210 // x = expr;
2211 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002212 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002213 // OpenMP, 2.12.6, atomic Construct
2214 // Any atomic construct with a seq_cst clause forces the atomically
2215 // performed operation to include an implicit flush operation without a
2216 // list.
2217 if (IsSeqCst)
2218 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2219}
2220
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002221static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2222 RValue Update,
2223 BinaryOperatorKind BO,
2224 llvm::AtomicOrdering AO,
2225 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002226 auto &Context = CGF.CGM.getContext();
2227 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002228 // expression is simple and atomic is allowed for the given type for the
2229 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002230 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002231 !Update.getScalarVal()->getType()->isIntegerTy() ||
2232 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2233 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002234 X.getAddress().getElementType())) ||
2235 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002236 !Context.getTargetInfo().hasBuiltinAtomic(
2237 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002238 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002239
2240 llvm::AtomicRMWInst::BinOp RMWOp;
2241 switch (BO) {
2242 case BO_Add:
2243 RMWOp = llvm::AtomicRMWInst::Add;
2244 break;
2245 case BO_Sub:
2246 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002247 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002248 RMWOp = llvm::AtomicRMWInst::Sub;
2249 break;
2250 case BO_And:
2251 RMWOp = llvm::AtomicRMWInst::And;
2252 break;
2253 case BO_Or:
2254 RMWOp = llvm::AtomicRMWInst::Or;
2255 break;
2256 case BO_Xor:
2257 RMWOp = llvm::AtomicRMWInst::Xor;
2258 break;
2259 case BO_LT:
2260 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2261 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2262 : llvm::AtomicRMWInst::Max)
2263 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2264 : llvm::AtomicRMWInst::UMax);
2265 break;
2266 case BO_GT:
2267 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2268 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2269 : llvm::AtomicRMWInst::Min)
2270 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2271 : llvm::AtomicRMWInst::UMin);
2272 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002273 case BO_Assign:
2274 RMWOp = llvm::AtomicRMWInst::Xchg;
2275 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002276 case BO_Mul:
2277 case BO_Div:
2278 case BO_Rem:
2279 case BO_Shl:
2280 case BO_Shr:
2281 case BO_LAnd:
2282 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002283 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002284 case BO_PtrMemD:
2285 case BO_PtrMemI:
2286 case BO_LE:
2287 case BO_GE:
2288 case BO_EQ:
2289 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002290 case BO_AddAssign:
2291 case BO_SubAssign:
2292 case BO_AndAssign:
2293 case BO_OrAssign:
2294 case BO_XorAssign:
2295 case BO_MulAssign:
2296 case BO_DivAssign:
2297 case BO_RemAssign:
2298 case BO_ShlAssign:
2299 case BO_ShrAssign:
2300 case BO_Comma:
2301 llvm_unreachable("Unsupported atomic update operation");
2302 }
2303 auto *UpdateVal = Update.getScalarVal();
2304 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2305 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002306 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002307 X.getType()->hasSignedIntegerRepresentation());
2308 }
John McCall7f416cc2015-09-08 08:05:57 +00002309 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002310 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002311}
2312
Alexey Bataev5e018f92015-04-23 06:35:10 +00002313std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002314 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2315 llvm::AtomicOrdering AO, SourceLocation Loc,
2316 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2317 // Update expressions are allowed to have the following forms:
2318 // x binop= expr; -> xrval + expr;
2319 // x++, ++x -> xrval + 1;
2320 // x--, --x -> xrval - 1;
2321 // x = x binop expr; -> xrval binop expr
2322 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002323 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2324 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002325 if (X.isGlobalReg()) {
2326 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2327 // 'xrval'.
2328 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2329 } else {
2330 // Perform compare-and-swap procedure.
2331 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002332 }
2333 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002334 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002335}
2336
2337static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2338 const Expr *X, const Expr *E,
2339 const Expr *UE, bool IsXLHSInRHSPart,
2340 SourceLocation Loc) {
2341 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2342 "Update expr in 'atomic update' must be a binary operator.");
2343 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2344 // Update expressions are allowed to have the following forms:
2345 // x binop= expr; -> xrval + expr;
2346 // x++, ++x -> xrval + 1;
2347 // x--, --x -> xrval - 1;
2348 // x = x binop expr; -> xrval binop expr
2349 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002350 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002351 LValue XLValue = CGF.EmitLValue(X);
2352 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002353 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002354 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2355 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2356 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2357 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2358 auto Gen =
2359 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2360 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2361 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2362 return CGF.EmitAnyExpr(UE);
2363 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002364 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2365 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2366 // OpenMP, 2.12.6, atomic Construct
2367 // Any atomic construct with a seq_cst clause forces the atomically
2368 // performed operation to include an implicit flush operation without a
2369 // list.
2370 if (IsSeqCst)
2371 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2372}
2373
2374static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002375 QualType SourceType, QualType ResType,
2376 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002377 switch (CGF.getEvaluationKind(ResType)) {
2378 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002379 return RValue::get(
2380 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002381 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002382 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002383 return RValue::getComplex(Res.first, Res.second);
2384 }
2385 case TEK_Aggregate:
2386 break;
2387 }
2388 llvm_unreachable("Must be a scalar or complex.");
2389}
2390
2391static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2392 bool IsPostfixUpdate, const Expr *V,
2393 const Expr *X, const Expr *E,
2394 const Expr *UE, bool IsXLHSInRHSPart,
2395 SourceLocation Loc) {
2396 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2397 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2398 RValue NewVVal;
2399 LValue VLValue = CGF.EmitLValue(V);
2400 LValue XLValue = CGF.EmitLValue(X);
2401 RValue ExprRValue = CGF.EmitAnyExpr(E);
2402 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2403 QualType NewVValType;
2404 if (UE) {
2405 // 'x' is updated with some additional value.
2406 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2407 "Update expr in 'atomic capture' must be a binary operator.");
2408 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2409 // Update expressions are allowed to have the following forms:
2410 // x binop= expr; -> xrval + expr;
2411 // x++, ++x -> xrval + 1;
2412 // x--, --x -> xrval - 1;
2413 // x = x binop expr; -> xrval binop expr
2414 // x = expr Op x; - > expr binop xrval;
2415 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2416 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2417 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2418 NewVValType = XRValExpr->getType();
2419 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2420 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2421 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2422 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2423 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2424 RValue Res = CGF.EmitAnyExpr(UE);
2425 NewVVal = IsPostfixUpdate ? XRValue : Res;
2426 return Res;
2427 };
2428 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2429 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2430 if (Res.first) {
2431 // 'atomicrmw' instruction was generated.
2432 if (IsPostfixUpdate) {
2433 // Use old value from 'atomicrmw'.
2434 NewVVal = Res.second;
2435 } else {
2436 // 'atomicrmw' does not provide new value, so evaluate it using old
2437 // value of 'x'.
2438 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2439 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2440 NewVVal = CGF.EmitAnyExpr(UE);
2441 }
2442 }
2443 } else {
2444 // 'x' is simply rewritten with some 'expr'.
2445 NewVValType = X->getType().getNonReferenceType();
2446 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002447 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002448 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2449 NewVVal = XRValue;
2450 return ExprRValue;
2451 };
2452 // Try to perform atomicrmw xchg, otherwise simple exchange.
2453 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2454 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2455 Loc, Gen);
2456 if (Res.first) {
2457 // 'atomicrmw' instruction was generated.
2458 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2459 }
2460 }
2461 // Emit post-update store to 'v' of old/new 'x' value.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002462 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002463 // OpenMP, 2.12.6, atomic Construct
2464 // Any atomic construct with a seq_cst clause forces the atomically
2465 // performed operation to include an implicit flush operation without a
2466 // list.
2467 if (IsSeqCst)
2468 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2469}
2470
Alexey Bataevb57056f2015-01-22 06:17:56 +00002471static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002472 bool IsSeqCst, bool IsPostfixUpdate,
2473 const Expr *X, const Expr *V, const Expr *E,
2474 const Expr *UE, bool IsXLHSInRHSPart,
2475 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002476 switch (Kind) {
2477 case OMPC_read:
2478 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2479 break;
2480 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002481 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2482 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002483 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002484 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002485 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2486 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002487 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002488 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2489 IsXLHSInRHSPart, Loc);
2490 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002491 case OMPC_if:
2492 case OMPC_final:
2493 case OMPC_num_threads:
2494 case OMPC_private:
2495 case OMPC_firstprivate:
2496 case OMPC_lastprivate:
2497 case OMPC_reduction:
2498 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002499 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002500 case OMPC_collapse:
2501 case OMPC_default:
2502 case OMPC_seq_cst:
2503 case OMPC_shared:
2504 case OMPC_linear:
2505 case OMPC_aligned:
2506 case OMPC_copyin:
2507 case OMPC_copyprivate:
2508 case OMPC_flush:
2509 case OMPC_proc_bind:
2510 case OMPC_schedule:
2511 case OMPC_ordered:
2512 case OMPC_nowait:
2513 case OMPC_untied:
2514 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002515 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002516 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002517 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002518 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002519 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002520 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002521 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002522 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002523 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002524 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002525 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002526 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002527 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002528 case OMPC_dist_schedule:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002529 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2530 }
2531}
2532
2533void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002534 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002535 OpenMPClauseKind Kind = OMPC_unknown;
2536 for (auto *C : S.clauses()) {
2537 // Find first clause (skip seq_cst clause, if it is first).
2538 if (C->getClauseKind() != OMPC_seq_cst) {
2539 Kind = C->getClauseKind();
2540 break;
2541 }
2542 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002543
2544 const auto *CS =
2545 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002546 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002547 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002548 }
2549 // Processing for statements under 'atomic capture'.
2550 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2551 for (const auto *C : Compound->body()) {
2552 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2553 enterFullExpression(EWC);
2554 }
2555 }
2556 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002557
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002558 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev33c56402015-12-14 09:26:19 +00002559 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2560 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002561 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2562 S.getV(), S.getExpr(), S.getUpdateExpr(),
2563 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002564 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002565 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002566}
2567
Samuel Antaobed3c462015-10-02 16:14:20 +00002568void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
2569 LexicalScope Scope(*this, S.getSourceRange());
2570 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2571
2572 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002573 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002574
Samuel Antaoee8fb302016-01-06 13:42:12 +00002575 llvm::Function *Fn = nullptr;
2576 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002577
2578 // Check if we have any if clause associated with the directive.
2579 const Expr *IfCond = nullptr;
2580
2581 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2582 IfCond = C->getCondition();
2583 }
2584
2585 // Check if we have any device clause associated with the directive.
2586 const Expr *Device = nullptr;
2587 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2588 Device = C->getDevice();
2589 }
2590
Samuel Antaoee8fb302016-01-06 13:42:12 +00002591 // Check if we have an if clause whose conditional always evaluates to false
2592 // or if we do not have any targets specified. If so the target region is not
2593 // an offload entry point.
2594 bool IsOffloadEntry = true;
2595 if (IfCond) {
2596 bool Val;
2597 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2598 IsOffloadEntry = false;
2599 }
2600 if (CGM.getLangOpts().OMPTargetTriples.empty())
2601 IsOffloadEntry = false;
2602
2603 assert(CurFuncDecl && "No parent declaration for target region!");
2604 StringRef ParentName;
2605 // In case we have Ctors/Dtors we use the complete type variant to produce
2606 // the mangling of the device outlined kernel.
2607 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2608 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2609 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2610 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2611 else
2612 ParentName =
2613 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2614
2615 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2616 IsOffloadEntry);
2617
2618 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002619 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002620}
2621
Alexey Bataev13314bf2014-10-09 04:18:56 +00002622void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2623 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2624}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002625
2626void CodeGenFunction::EmitOMPCancellationPointDirective(
2627 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002628 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2629 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002630}
2631
Alexey Bataev80909872015-07-02 11:25:17 +00002632void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002633 const Expr *IfCond = nullptr;
2634 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2635 if (C->getNameModifier() == OMPD_unknown ||
2636 C->getNameModifier() == OMPD_cancel) {
2637 IfCond = C->getCondition();
2638 break;
2639 }
2640 }
2641 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002642 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002643}
2644
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002645CodeGenFunction::JumpDest
2646CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2647 if (Kind == OMPD_parallel || Kind == OMPD_task)
2648 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002649 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
2650 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
2651 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002652}
Michael Wong65f367f2015-07-21 13:44:28 +00002653
2654// Generate the instructions for '#pragma omp target data' directive.
2655void CodeGenFunction::EmitOMPTargetDataDirective(
2656 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002657 // emit the code inside the construct for now
2658 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002659 CGM.getOpenMPRuntime().emitInlinedDirective(
2660 *this, OMPD_target_data,
2661 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002662}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002663
Samuel Antaodf67fc42016-01-19 19:15:56 +00002664void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2665 const OMPTargetEnterDataDirective &S) {
2666 // TODO: codegen for target enter data.
2667}
2668
Alexey Bataev49f6e782015-12-01 04:18:41 +00002669void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2670 // emit the code inside the construct for now
2671 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2672 CGM.getOpenMPRuntime().emitInlinedDirective(
2673 *this, OMPD_taskloop,
2674 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2675}
2676
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002677void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2678 const OMPTaskLoopSimdDirective &S) {
2679 // emit the code inside the construct for now
2680 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2681 CGM.getOpenMPRuntime().emitInlinedDirective(
2682 *this, OMPD_taskloop_simd,
2683 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2684}
2685