blob: 2ea9b0fa6369e626ee736d36c3b3c1866194d055 [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 Bataev1189bd02016-01-26 12:20:39 +000023llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
24 auto &C = getContext();
25 llvm::Value *Size = nullptr;
26 auto SizeInChars = C.getTypeSizeInChars(Ty);
27 if (SizeInChars.isZero()) {
28 // getTypeSizeInChars() returns 0 for a VLA.
29 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
30 llvm::Value *ArraySize;
31 std::tie(ArraySize, Ty) = getVLASize(VAT);
32 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
33 }
34 SizeInChars = C.getTypeSizeInChars(Ty);
35 if (SizeInChars.isZero())
36 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
37 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
38 } else
39 Size = CGM.getSize(SizeInChars);
40 return Size;
41}
42
Alexey Bataev2377fe92015-09-10 08:12:02 +000043void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000044 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000045 const RecordDecl *RD = S.getCapturedRecordDecl();
46 auto CurField = RD->field_begin();
47 auto CurCap = S.captures().begin();
48 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
49 E = S.capture_init_end();
50 I != E; ++I, ++CurField, ++CurCap) {
51 if (CurField->hasCapturedVLAType()) {
52 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000053 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000054 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000055 } else if (CurCap->capturesThis())
56 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000057 else if (CurCap->capturesVariableByCopy())
58 CapturedVars.push_back(
59 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
60 else {
61 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000062 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000063 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000064 }
65}
66
Samuel Antao4af1b7b2015-12-02 17:44:43 +000067static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
68 StringRef Name, LValue AddrLV,
69 bool isReferenceType = false) {
70 ASTContext &Ctx = CGF.getContext();
71
72 auto *CastedPtr = CGF.EmitScalarConversion(
73 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
74 Ctx.getPointerType(DstType), SourceLocation());
75 auto TmpAddr =
76 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
77 .getAddress();
78
79 // If we are dealing with references we need to return the address of the
80 // reference instead of the reference of the value.
81 if (isReferenceType) {
82 QualType RefType = Ctx.getLValueReferenceType(DstType);
83 auto *RefVal = TmpAddr.getPointer();
84 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
85 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
86 CGF.EmitScalarInit(RefVal, TmpLVal);
87 }
88
89 return TmpAddr;
90}
91
Alexey Bataev2377fe92015-09-10 08:12:02 +000092llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +000093CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000094 assert(
95 CapturedStmtInfo &&
96 "CapturedStmtInfo should be set when generating the captured function");
97 const CapturedDecl *CD = S.getCapturedDecl();
98 const RecordDecl *RD = S.getCapturedRecordDecl();
99 assert(CD->hasBody() && "missing CapturedDecl body");
100
101 // Build the argument list.
102 ASTContext &Ctx = CGM.getContext();
103 FunctionArgList Args;
104 Args.append(CD->param_begin(),
105 std::next(CD->param_begin(), CD->getContextParamPosition()));
106 auto I = S.captures().begin();
107 for (auto *FD : RD->fields()) {
108 QualType ArgType = FD->getType();
109 IdentifierInfo *II = nullptr;
110 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000111
112 // If this is a capture by copy and the type is not a pointer, the outlined
113 // function argument type should be uintptr and the value properly casted to
114 // uintptr. This is necessary given that the runtime library is only able to
115 // deal with pointers. We can pass in the same way the VLA type sizes to the
116 // outlined function.
117 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
118 I->capturesVariableArrayType())
119 ArgType = Ctx.getUIntPtrType();
120
121 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000122 CapVar = I->getCapturedVar();
123 II = CapVar->getIdentifier();
124 } else if (I->capturesThis())
125 II = &getContext().Idents.get("this");
126 else {
127 assert(I->capturesVariableArrayType());
128 II = &getContext().Idents.get("vla");
129 }
130 if (ArgType->isVariablyModifiedType())
131 ArgType = getContext().getVariableArrayDecayedType(ArgType);
132 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
133 FD->getLocation(), II, ArgType));
134 ++I;
135 }
136 Args.append(
137 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
138 CD->param_end());
139
140 // Create the function declaration.
141 FunctionType::ExtInfo ExtInfo;
142 const CGFunctionInfo &FuncInfo =
143 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
144 /*IsVariadic=*/false);
145 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
146
147 llvm::Function *F = llvm::Function::Create(
148 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
149 CapturedStmtInfo->getHelperName(), &CGM.getModule());
150 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
151 if (CD->isNothrow())
152 F->addFnAttr(llvm::Attribute::NoUnwind);
153
154 // Generate the function.
155 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
156 CD->getBody()->getLocStart());
157 unsigned Cnt = CD->getContextParamPosition();
158 I = S.captures().begin();
159 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000160 // If we are capturing a pointer by copy we don't need to do anything, just
161 // use the value that we get from the arguments.
162 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
163 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
164 ++Cnt, ++I;
165 continue;
166 }
167
Alexey Bataev2377fe92015-09-10 08:12:02 +0000168 LValue ArgLVal =
169 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
170 AlignmentSource::Decl);
171 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000172 LValue CastedArgLVal =
173 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
174 Args[Cnt]->getName(), ArgLVal),
175 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000176 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000177 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000178 auto VAT = FD->getCapturedVLAType();
179 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
180 } else if (I->capturesVariable()) {
181 auto *Var = I->getCapturedVar();
182 QualType VarTy = Var->getType();
183 Address ArgAddr = ArgLVal.getAddress();
184 if (!VarTy->isReferenceType()) {
185 ArgAddr = EmitLoadOfReference(
186 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
187 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000188 setAddrOfLocalVar(
189 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000190 } else if (I->capturesVariableByCopy()) {
191 assert(!FD->getType()->isAnyPointerType() &&
192 "Not expecting a captured pointer.");
193 auto *Var = I->getCapturedVar();
194 QualType VarTy = Var->getType();
195 setAddrOfLocalVar(I->getCapturedVar(),
196 castValueFromUintptr(*this, FD->getType(),
197 Args[Cnt]->getName(), ArgLVal,
198 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000199 } else {
200 // If 'this' is captured, load it into CXXThisValue.
201 assert(I->capturesThis());
202 CXXThisValue =
203 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
204 }
205 ++Cnt, ++I;
206 }
207
Serge Pavlov3a561452015-12-06 14:32:39 +0000208 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000209 CapturedStmtInfo->EmitBody(*this, CD->getBody());
210 FinishFunction(CD->getBodyRBrace());
211
212 return F;
213}
214
Alexey Bataev9959db52014-05-06 10:08:46 +0000215//===----------------------------------------------------------------------===//
216// OpenMP Directive Emission
217//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000218void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000219 Address DestAddr, Address SrcAddr, QualType OriginalType,
220 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000221 // Perform element-by-element initialization.
222 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000223
224 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000225 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000226 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
227 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
228
229 auto SrcBegin = SrcAddr.getPointer();
230 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000231 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000232 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
233 // The basic structure here is a while-do loop.
234 auto BodyBB = createBasicBlock("omp.arraycpy.body");
235 auto DoneBB = createBasicBlock("omp.arraycpy.done");
236 auto IsEmpty =
237 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
238 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000239
Alexey Bataev420d45b2015-04-14 05:11:24 +0000240 // Enter the loop body, making that address the current address.
241 auto EntryBB = Builder.GetInsertBlock();
242 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000243
244 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
245
246 llvm::PHINode *SrcElementPHI =
247 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
248 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
249 Address SrcElementCurrent =
250 Address(SrcElementPHI,
251 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
252
253 llvm::PHINode *DestElementPHI =
254 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
255 DestElementPHI->addIncoming(DestBegin, EntryBB);
256 Address DestElementCurrent =
257 Address(DestElementPHI,
258 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000259
Alexey Bataev420d45b2015-04-14 05:11:24 +0000260 // Emit copy.
261 CopyGen(DestElementCurrent, SrcElementCurrent);
262
263 // Shift the address forward by one element.
264 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000265 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000266 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000267 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000268 // Check whether we've reached the end.
269 auto Done =
270 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
271 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000272 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
273 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000274
275 // Done.
276 EmitBlock(DoneBB, /*IsFinished=*/true);
277}
278
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000279/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000280/// \param DestAddr Address of the array.
281/// \param Type Type of array.
282/// \param Init Initial expression of array.
283static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
284 QualType Type, const Expr *Init) {
285 // Perform element-by-element initialization.
286 QualType ElementTy;
287
288 // Drill down to the base element type on both arrays.
289 auto ArrayTy = Type->getAsArrayTypeUnsafe();
290 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
291 DestAddr =
292 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
293
294 auto DestBegin = DestAddr.getPointer();
295 // Cast from pointer to array type to pointer to single element.
296 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
297 // The basic structure here is a while-do loop.
298 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
299 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
300 auto IsEmpty =
301 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
302 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
303
304 // Enter the loop body, making that address the current address.
305 auto EntryBB = CGF.Builder.GetInsertBlock();
306 CGF.EmitBlock(BodyBB);
307
308 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
309
310 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
311 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
312 DestElementPHI->addIncoming(DestBegin, EntryBB);
313 Address DestElementCurrent =
314 Address(DestElementPHI,
315 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
316
317 // Emit copy.
318 {
319 CodeGenFunction::RunCleanupsScope InitScope(CGF);
320 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
321 /*IsInitializer=*/false);
322 }
323
324 // Shift the address forward by one element.
325 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
326 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
327 // Check whether we've reached the end.
328 auto Done =
329 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
330 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
331 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
332
333 // Done.
334 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
335}
336
John McCall7f416cc2015-09-08 08:05:57 +0000337void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
338 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000339 const VarDecl *SrcVD, const Expr *Copy) {
340 if (OriginalType->isArrayType()) {
341 auto *BO = dyn_cast<BinaryOperator>(Copy);
342 if (BO && BO->getOpcode() == BO_Assign) {
343 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000344 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000345 } else {
346 // For arrays with complex element types perform element by element
347 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000348 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000349 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000350 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000351 // Working with the single array element, so have to remap
352 // destination and source variables to corresponding array
353 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000354 CodeGenFunction::OMPPrivateScope Remap(*this);
355 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000356 return DestElement;
357 });
358 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000359 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000360 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000361 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000362 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000363 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000364 } else {
365 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000366 CodeGenFunction::OMPPrivateScope Remap(*this);
367 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
368 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000369 (void)Remap.Privatize();
370 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000371 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000372 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000373}
374
Alexey Bataev69c62a92015-04-15 04:52:20 +0000375bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
376 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000377 if (!HaveInsertPoint())
378 return false;
Alexey Bataev69c62a92015-04-15 04:52:20 +0000379 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000380 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000381 auto IRef = C->varlist_begin();
382 auto InitsRef = C->inits().begin();
383 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000384 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000385 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
386 EmittedAsFirstprivate.insert(OrigVD);
387 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
388 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
389 bool IsRegistered;
390 DeclRefExpr DRE(
391 const_cast<VarDecl *>(OrigVD),
392 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
393 OrigVD) != nullptr,
394 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000395 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000396 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000397 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000398 // Emit VarDecl with copy init for arrays.
399 // Get the address of the original variable captured in current
400 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000401 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000402 auto Emission = EmitAutoVarAlloca(*VD);
403 auto *Init = VD->getInit();
404 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
405 // Perform simple memcpy.
406 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000407 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000408 } else {
409 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000410 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000411 [this, VDInit, Init](Address DestElement,
412 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000413 // Clean up any temporaries needed by the initialization.
414 RunCleanupsScope InitScope(*this);
415 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000416 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000417 EmitAnyExprToMem(Init, DestElement,
418 Init->getType().getQualifiers(),
419 /*IsInitializer*/ false);
420 LocalDeclMap.erase(VDInit);
421 });
422 }
423 EmitAutoVarCleanups(Emission);
424 return Emission.getAllocatedAddress();
425 });
426 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000427 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000428 // Emit private VarDecl with copy init.
429 // Remap temp VDInit variable to the address of the original
430 // variable
431 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000432 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000433 EmitDecl(*VD);
434 LocalDeclMap.erase(VDInit);
435 return GetAddrOfLocalVar(VD);
436 });
437 }
438 assert(IsRegistered &&
439 "firstprivate var already registered as private");
440 // Silence the warning about unused variable.
441 (void)IsRegistered;
442 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000443 ++IRef, ++InitsRef;
444 }
445 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000446 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000447}
448
Alexey Bataev03b340a2014-10-21 03:16:40 +0000449void CodeGenFunction::EmitOMPPrivateClause(
450 const OMPExecutableDirective &D,
451 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000452 if (!HaveInsertPoint())
453 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000454 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000455 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000456 auto IRef = C->varlist_begin();
457 for (auto IInit : C->private_copies()) {
458 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000459 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
460 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
461 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000462 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000463 // Emit private VarDecl with copy init.
464 EmitDecl(*VD);
465 return GetAddrOfLocalVar(VD);
466 });
467 assert(IsRegistered && "private var already registered as private");
468 // Silence the warning about unused variable.
469 (void)IsRegistered;
470 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000471 ++IRef;
472 }
473 }
474}
475
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000476bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000477 if (!HaveInsertPoint())
478 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000479 // threadprivate_var1 = master_threadprivate_var1;
480 // operator=(threadprivate_var2, master_threadprivate_var2);
481 // ...
482 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000483 llvm::DenseSet<const VarDecl *> CopiedVars;
484 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000485 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000486 auto IRef = C->varlist_begin();
487 auto ISrcRef = C->source_exprs().begin();
488 auto IDestRef = C->destination_exprs().begin();
489 for (auto *AssignOp : C->assignment_ops()) {
490 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000491 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000492 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000493
494 // Get the address of the master variable. If we are emitting code with
495 // TLS support, the address is passed from the master as field in the
496 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000497 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000498 if (getLangOpts().OpenMPUseTLS &&
499 getContext().getTargetInfo().isTLSSupported()) {
500 assert(CapturedStmtInfo->lookup(VD) &&
501 "Copyin threadprivates should have been captured!");
502 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
503 VK_LValue, (*IRef)->getExprLoc());
504 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000506 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000507 MasterAddr =
508 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
509 : CGM.GetAddrOfGlobal(VD),
510 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000511 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000512 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000513 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000514 if (CopiedVars.size() == 1) {
515 // At first check if current thread is a master thread. If it is, no
516 // need to copy data.
517 CopyBegin = createBasicBlock("copyin.not.master");
518 CopyEnd = createBasicBlock("copyin.not.master.end");
519 Builder.CreateCondBr(
520 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000521 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
522 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000523 CopyBegin, CopyEnd);
524 EmitBlock(CopyBegin);
525 }
526 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
527 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000528 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000529 }
530 ++IRef;
531 ++ISrcRef;
532 ++IDestRef;
533 }
534 }
535 if (CopyEnd) {
536 // Exit out of copying procedure for non-master thread.
537 EmitBlock(CopyEnd, /*IsFinished=*/true);
538 return true;
539 }
540 return false;
541}
542
Alexey Bataev38e89532015-04-16 04:54:05 +0000543bool CodeGenFunction::EmitOMPLastprivateClauseInit(
544 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000545 if (!HaveInsertPoint())
546 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000547 bool HasAtLeastOneLastprivate = false;
548 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000549 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000550 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000551 auto IRef = C->varlist_begin();
552 auto IDestRef = C->destination_exprs().begin();
553 for (auto *IInit : C->private_copies()) {
554 // Keep the address of the original variable for future update at the end
555 // of the loop.
556 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
557 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
558 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000559 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000560 DeclRefExpr DRE(
561 const_cast<VarDecl *>(OrigVD),
562 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
563 OrigVD) != nullptr,
564 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
565 return EmitLValue(&DRE).getAddress();
566 });
567 // Check if the variable is also a firstprivate: in this case IInit is
568 // not generated. Initialization of this variable will happen in codegen
569 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000570 if (IInit) {
571 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
572 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000573 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000574 // Emit private VarDecl with copy init.
575 EmitDecl(*VD);
576 return GetAddrOfLocalVar(VD);
577 });
578 assert(IsRegistered &&
579 "lastprivate var already registered as private");
580 (void)IsRegistered;
581 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000582 }
583 ++IRef, ++IDestRef;
584 }
585 }
586 return HasAtLeastOneLastprivate;
587}
588
589void CodeGenFunction::EmitOMPLastprivateClauseFinal(
590 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000591 if (!HaveInsertPoint())
592 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000593 // Emit following code:
594 // if (<IsLastIterCond>) {
595 // orig_var1 = private_orig_var1;
596 // ...
597 // orig_varn = private_orig_varn;
598 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000599 llvm::BasicBlock *ThenBB = nullptr;
600 llvm::BasicBlock *DoneBB = nullptr;
601 if (IsLastIterCond) {
602 ThenBB = createBasicBlock(".omp.lastprivate.then");
603 DoneBB = createBasicBlock(".omp.lastprivate.done");
604 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
605 EmitBlock(ThenBB);
606 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000607 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
608 const Expr *LastIterVal = nullptr;
609 const Expr *IVExpr = nullptr;
610 const Expr *IncExpr = nullptr;
611 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000612 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
613 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
614 LoopDirective->getUpperBoundVariable())
615 ->getDecl())
616 ->getAnyInitializer();
617 IVExpr = LoopDirective->getIterationVariable();
618 IncExpr = LoopDirective->getInc();
619 auto IUpdate = LoopDirective->updates().begin();
620 for (auto *E : LoopDirective->counters()) {
621 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
622 LoopCountersAndUpdates[D] = *IUpdate;
623 ++IUpdate;
624 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000625 }
626 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000627 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000628 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000629 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000630 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000631 auto IRef = C->varlist_begin();
632 auto ISrcRef = C->source_exprs().begin();
633 auto IDestRef = C->destination_exprs().begin();
634 for (auto *AssignOp : C->assignment_ops()) {
635 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000636 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000637 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
638 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
639 // If lastprivate variable is a loop control variable for loop-based
640 // directive, update its value before copyin back to original
641 // variable.
642 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000643 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000644 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
645 IVExpr->getType().getQualifiers(),
646 /*IsInitializer=*/false);
647 EmitIgnoredExpr(IncExpr);
648 FirstLCV = false;
649 }
650 EmitIgnoredExpr(UpExpr);
651 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000652 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
653 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
654 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000655 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000656 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000657 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
658 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000659 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000660 Address(Builder.CreateLoad(PrivateAddr),
661 getNaturalTypeAlignment(RefTy->getPointeeType()));
662 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000663 }
664 ++IRef;
665 ++ISrcRef;
666 ++IDestRef;
667 }
668 }
669 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000670 if (IsLastIterCond) {
671 EmitBlock(DoneBB, /*IsFinished=*/true);
672 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000673}
674
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000675void CodeGenFunction::EmitOMPReductionClauseInit(
676 const OMPExecutableDirective &D,
677 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000678 if (!HaveInsertPoint())
679 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000680 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000681 auto ILHS = C->lhs_exprs().begin();
682 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000683 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000684 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000685 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000686 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
687 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
688 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
689 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
690 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
691 Base = TempOASE->getBase()->IgnoreParenImpCasts();
692 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
693 Base = TempASE->getBase()->IgnoreParenImpCasts();
694 auto *DE = cast<DeclRefExpr>(Base);
695 auto *OrigVD = cast<VarDecl>(DE->getDecl());
696 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
697 auto OASELValueUB =
698 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
699 auto OriginalBaseLValue = EmitLValue(DE);
700 auto BaseLValue = OriginalBaseLValue;
701 auto *Zero = Builder.getInt64(/*C=*/0);
702 llvm::SmallVector<llvm::Value *, 4> Indexes;
703 Indexes.push_back(Zero);
704 auto *ItemTy =
705 OASELValueLB.getPointer()->getType()->getPointerElementType();
706 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
707 while (Ty != ItemTy) {
708 Indexes.push_back(Zero);
709 Ty = Ty->getPointerElementType();
710 }
711 BaseLValue = MakeAddrLValue(
712 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
713 OASELValueLB.getAlignment()),
714 OASELValueLB.getType(), OASELValueLB.getAlignmentSource());
715 // Store the address of the original variable associated with the LHS
716 // implicit variable.
717 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
718 return OASELValueLB.getAddress();
719 });
720 // Emit reduction copy.
721 bool IsRegistered = PrivateScope.addPrivate(
722 OrigVD, [this, PrivateVD, BaseLValue, OASELValueLB, OASELValueUB,
723 OriginalBaseLValue]() -> Address {
724 // Emit VarDecl with copy init for arrays.
725 // Get the address of the original variable captured in current
726 // captured region.
727 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
728 OASELValueLB.getPointer());
729 Size = Builder.CreateNUWAdd(
730 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
731 CodeGenFunction::OpaqueValueMapping OpaqueMap(
732 *this, cast<OpaqueValueExpr>(
733 getContext()
734 .getAsVariableArrayType(PrivateVD->getType())
735 ->getSizeExpr()),
736 RValue::get(Size));
737 EmitVariablyModifiedType(PrivateVD->getType());
738 auto Emission = EmitAutoVarAlloca(*PrivateVD);
739 auto Addr = Emission.getAllocatedAddress();
740 auto *Init = PrivateVD->getInit();
741 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
742 EmitAutoVarCleanups(Emission);
743 // Emit private VarDecl with reduction init.
744 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
745 OASELValueLB.getPointer());
746 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
747 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
748 Ptr, OriginalBaseLValue.getPointer()->getType());
749 return Address(Ptr, OriginalBaseLValue.getAlignment());
750 });
751 assert(IsRegistered && "private var already registered as private");
752 // Silence the warning about unused variable.
753 (void)IsRegistered;
754 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
755 return GetAddrOfLocalVar(PrivateVD);
756 });
757 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
758 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
759 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
760 Base = TempASE->getBase()->IgnoreParenImpCasts();
761 auto *DE = cast<DeclRefExpr>(Base);
762 auto *OrigVD = cast<VarDecl>(DE->getDecl());
763 auto ASELValue = EmitLValue(ASE);
764 auto OriginalBaseLValue = EmitLValue(DE);
765 auto BaseLValue = OriginalBaseLValue;
766 auto *Zero = Builder.getInt64(/*C=*/0);
767 llvm::SmallVector<llvm::Value *, 4> Indexes;
768 Indexes.push_back(Zero);
769 auto *ItemTy =
770 ASELValue.getPointer()->getType()->getPointerElementType();
771 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
772 while (Ty != ItemTy) {
773 Indexes.push_back(Zero);
774 Ty = Ty->getPointerElementType();
775 }
776 BaseLValue = MakeAddrLValue(
777 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
778 ASELValue.getAlignment()),
779 ASELValue.getType(), ASELValue.getAlignmentSource());
780 // Store the address of the original variable associated with the LHS
781 // implicit variable.
782 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
783 return ASELValue.getAddress();
784 });
785 // Emit reduction copy.
786 bool IsRegistered = PrivateScope.addPrivate(
787 OrigVD, [this, PrivateVD, BaseLValue, ASELValue,
788 OriginalBaseLValue]() -> Address {
789 // Emit private VarDecl with reduction init.
790 EmitDecl(*PrivateVD);
791 auto Addr = GetAddrOfLocalVar(PrivateVD);
792 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
793 ASELValue.getPointer());
794 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
795 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
796 Ptr, OriginalBaseLValue.getPointer()->getType());
797 return Address(Ptr, OriginalBaseLValue.getAlignment());
798 });
799 assert(IsRegistered && "private var already registered as private");
800 // Silence the warning about unused variable.
801 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000802 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
803 return Builder.CreateElementBitCast(
804 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
805 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000806 });
807 } else {
808 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000809 QualType Type = PrivateVD->getType();
810 if (getContext().getAsArrayType(Type)) {
811 // Store the address of the original variable associated with the LHS
812 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000813 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
814 CapturedStmtInfo->lookup(OrigVD) != nullptr,
815 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000816 Address OriginalAddr = EmitLValue(&DRE).getAddress();
817 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
818 LHSVD]() -> Address {
819 return Builder.CreateElementBitCast(
820 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
821 "lhs.begin");
822 });
823 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
824 if (Type->isVariablyModifiedType()) {
825 CodeGenFunction::OpaqueValueMapping OpaqueMap(
826 *this, cast<OpaqueValueExpr>(
827 getContext()
828 .getAsVariableArrayType(PrivateVD->getType())
829 ->getSizeExpr()),
830 RValue::get(
831 getTypeSize(OrigVD->getType().getNonReferenceType())));
832 EmitVariablyModifiedType(Type);
833 }
834 auto Emission = EmitAutoVarAlloca(*PrivateVD);
835 auto Addr = Emission.getAllocatedAddress();
836 auto *Init = PrivateVD->getInit();
837 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
838 EmitAutoVarCleanups(Emission);
839 return Emission.getAllocatedAddress();
840 });
841 assert(IsRegistered && "private var already registered as private");
842 // Silence the warning about unused variable.
843 (void)IsRegistered;
844 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
845 return Builder.CreateElementBitCast(
846 GetAddrOfLocalVar(PrivateVD),
847 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
848 });
849 } else {
850 // Store the address of the original variable associated with the LHS
851 // implicit variable.
852 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
853 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
854 CapturedStmtInfo->lookup(OrigVD) != nullptr,
855 IRef->getType(), VK_LValue, IRef->getExprLoc());
856 return EmitLValue(&DRE).getAddress();
857 });
858 // Emit reduction copy.
859 bool IsRegistered =
860 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
861 // Emit private VarDecl with reduction init.
862 EmitDecl(*PrivateVD);
863 return GetAddrOfLocalVar(PrivateVD);
864 });
865 assert(IsRegistered && "private var already registered as private");
866 // Silence the warning about unused variable.
867 (void)IsRegistered;
868 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
869 return GetAddrOfLocalVar(PrivateVD);
870 });
871 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000872 }
873 ++ILHS, ++IRHS, ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000874 }
875 }
876}
877
878void CodeGenFunction::EmitOMPReductionClauseFinal(
879 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000880 if (!HaveInsertPoint())
881 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000882 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000883 llvm::SmallVector<const Expr *, 8> LHSExprs;
884 llvm::SmallVector<const Expr *, 8> RHSExprs;
885 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000886 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000887 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000888 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000889 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000890 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
891 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
892 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
893 }
894 if (HasAtLeastOneReduction) {
895 // Emit nowait reduction if nowait clause is present or directive is a
896 // parallel directive (it always has implicit barrier).
897 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000898 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000899 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000900 isOpenMPParallelDirective(D.getDirectiveKind()) ||
901 D.getDirectiveKind() == OMPD_simd,
902 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000903 }
904}
905
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000906static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
907 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000908 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000909 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000910 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000911 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
912 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000913 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000914 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000915 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000916 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000917 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
918 /*IgnoreResultAssign*/ true);
919 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
920 CGF, NumThreads, NumThreadsClause->getLocStart());
921 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000922 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000923 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000924 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
925 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
926 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000927 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000928 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
929 if (C->getNameModifier() == OMPD_unknown ||
930 C->getNameModifier() == OMPD_parallel) {
931 IfCond = C->getCondition();
932 break;
933 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000934 }
935 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000936 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000937}
938
939void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
940 LexicalScope Scope(*this, S.getSourceRange());
941 // Emit parallel region as a standalone region.
942 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
943 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000944 bool Copyins = CGF.EmitOMPCopyinClause(S);
945 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
946 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000947 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000948 // initialization of firstprivate variables or propagation master's thread
949 // values of threadprivate variables to local instances of that variables
950 // of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000951 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
952 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
953 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000954 }
955 CGF.EmitOMPPrivateClause(S, PrivateScope);
956 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
957 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000958 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000959 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000960 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000961 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000962}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000963
Alexey Bataev0f34da12015-07-02 04:17:07 +0000964void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
965 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000966 RunCleanupsScope BodyScope(*this);
967 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000968 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000969 EmitIgnoredExpr(I);
970 }
Alexander Musman3276a272015-03-21 10:12:56 +0000971 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000972 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000973 for (auto U : C->updates()) {
974 EmitIgnoredExpr(U);
975 }
976 }
977
Alexander Musmana5f070a2014-10-01 06:03:56 +0000978 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000979 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000980 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000981 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000982 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000983 // The end (updates/cleanups).
984 EmitBlock(Continue.getBlock());
985 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000986 // TODO: Update lastprivates if the SeparateIter flag is true.
987 // This will be implemented in a follow-up OMPLastprivateClause patch, but
988 // result should be still correct without it, as we do not make these
989 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000990}
991
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000992void CodeGenFunction::EmitOMPInnerLoop(
993 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
994 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000995 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
996 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000997 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000998
999 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001000 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001001 EmitBlock(CondBlock);
1002 LoopStack.push(CondBlock);
1003
1004 // If there are any cleanups between here and the loop-exit scope,
1005 // create a block to stage a loop exit along.
1006 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001007 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001008 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001009
Alexander Musmand196ef22014-10-07 08:57:09 +00001010 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001011
Alexey Bataev2df54a02015-03-12 08:53:29 +00001012 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001013 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001014 if (ExitBlock != LoopExit.getBlock()) {
1015 EmitBlock(ExitBlock);
1016 EmitBranchThroughCleanup(LoopExit);
1017 }
1018
1019 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001020 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001021
1022 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001023 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001024 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1025
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001026 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001027
1028 // Emit "IV = IV + 1" and a back-edge to the condition block.
1029 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001030 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001031 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001032 BreakContinueStack.pop_back();
1033 EmitBranch(CondBlock);
1034 LoopStack.pop();
1035 // Emit the fall-through block.
1036 EmitBlock(LoopExit.getBlock());
1037}
1038
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001039void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001040 if (!HaveInsertPoint())
1041 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001042 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001043 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001044 for (auto Init : C->inits()) {
1045 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001046 auto *OrigVD = cast<VarDecl>(
1047 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1048 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1049 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1050 VD->getInit()->getType(), VK_LValue,
1051 VD->getInit()->getExprLoc());
1052 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1053 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001054 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001055 /*capturedByInit=*/false);
1056 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001057 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001058 // Emit the linear steps for the linear clauses.
1059 // If a step is not constant, it is pre-calculated before the loop.
1060 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1061 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001062 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001063 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001064 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001065 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001066 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001067}
1068
1069static void emitLinearClauseFinal(CodeGenFunction &CGF,
1070 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001071 if (!CGF.HaveInsertPoint())
1072 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001073 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001074 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001075 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001076 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001077 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1078 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001079 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001080 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001081 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001082 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001083 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001084 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001085 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001086 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001087 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001088 }
1089 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001090}
1091
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001092static void emitAlignedClause(CodeGenFunction &CGF,
1093 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001094 if (!CGF.HaveInsertPoint())
1095 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001096 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001097 unsigned ClauseAlignment = 0;
1098 if (auto AlignmentExpr = Clause->getAlignment()) {
1099 auto AlignmentCI =
1100 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1101 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001102 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001103 for (auto E : Clause->varlists()) {
1104 unsigned Alignment = ClauseAlignment;
1105 if (Alignment == 0) {
1106 // OpenMP [2.8.1, Description]
1107 // If no optional parameter is specified, implementation-defined default
1108 // alignments for SIMD instructions on the target platforms are assumed.
1109 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001110 CGF.getContext()
1111 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1112 E->getType()->getPointeeType()))
1113 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001114 }
1115 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1116 "alignment is not power of 2");
1117 if (Alignment != 0) {
1118 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1119 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1120 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001121 }
1122 }
1123}
1124
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001125static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001126 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001127 ArrayRef<Expr *> Counters,
1128 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001129 if (!CGF.HaveInsertPoint())
1130 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001131 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001132 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001133 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1134 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001135 Address Addr = Address::invalid();
1136 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001137 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001138 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001139 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001140 Addr = VarEmission.getAllocatedAddress();
1141 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001142 });
John McCall7f416cc2015-09-08 08:05:57 +00001143 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001144 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001145 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001146}
1147
Alexey Bataev62dbb972015-04-22 11:59:37 +00001148static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1149 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1150 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001151 if (!CGF.HaveInsertPoint())
1152 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001153 {
1154 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001155 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1156 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001157 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001158 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001159 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001160 CGF.EmitIgnoredExpr(I);
1161 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001162 }
1163 // Check that loop is executed at least one time.
1164 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1165}
1166
Alexander Musman3276a272015-03-21 10:12:56 +00001167static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001168emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001169 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001170 if (!CGF.HaveInsertPoint())
1171 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001172 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001173 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001174 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001175 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1176 auto *PrivateVD =
1177 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001178 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001179 // Emit private VarDecl with copy init.
1180 CGF.EmitVarDecl(*PrivateVD);
1181 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001182 });
1183 assert(IsRegistered && "linear var already registered as private");
1184 // Silence the warning about unused variable.
1185 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001186 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001187 }
1188 }
1189}
1190
Alexey Bataev45bfad52015-08-21 12:19:04 +00001191static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001192 const OMPExecutableDirective &D,
1193 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001194 if (!CGF.HaveInsertPoint())
1195 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001196 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001197 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1198 /*ignoreResult=*/true);
1199 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1200 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1201 // In presence of finite 'safelen', it may be unsafe to mark all
1202 // the memory instructions parallel, because loop-carried
1203 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001204 if (!IsMonotonic)
1205 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001206 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001207 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1208 /*ignoreResult=*/true);
1209 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001210 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001211 // In presence of finite 'safelen', it may be unsafe to mark all
1212 // the memory instructions parallel, because loop-carried
1213 // dependences of 'safelen' iterations are possible.
1214 CGF.LoopStack.setParallel(false);
1215 }
1216}
1217
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001218void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1219 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001220 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001221 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001222 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001223 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001224}
1225
1226void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001227 if (!HaveInsertPoint())
1228 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001229 auto IC = D.counters().begin();
1230 for (auto F : D.finals()) {
1231 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001232 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001233 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1234 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1235 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001236 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001237 OMPPrivateScope VarScope(*this);
1238 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001239 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001240 (void)VarScope.Privatize();
1241 EmitIgnoredExpr(F);
1242 }
1243 ++IC;
1244 }
1245 emitLinearClauseFinal(*this, D);
1246}
1247
Alexander Musman515ad8c2014-05-22 08:54:05 +00001248void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001249 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001250 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001251 // for (IV in 0..LastIteration) BODY;
1252 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001253 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001254 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001255
Alexey Bataev62dbb972015-04-22 11:59:37 +00001256 // Emit: if (PreCond) - begin.
1257 // If the condition constant folds and can be elided, avoid emitting the
1258 // whole loop.
1259 bool CondConstant;
1260 llvm::BasicBlock *ContBlock = nullptr;
1261 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1262 if (!CondConstant)
1263 return;
1264 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001265 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1266 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001267 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1268 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001269 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001270 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001271 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001272
1273 // Emit the loop iteration variable.
1274 const Expr *IVExpr = S.getIterationVariable();
1275 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1276 CGF.EmitVarDecl(*IVDecl);
1277 CGF.EmitIgnoredExpr(S.getInit());
1278
1279 // Emit the iterations count variable.
1280 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001281 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1283 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1284 // Emit calculation of the iterations count.
1285 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001286 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001287
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001288 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001289
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001290 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001291 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001292 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001293 {
1294 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001295 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1296 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001297 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001298 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001299 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001300 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001301 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001302 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1303 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001304 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001305 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001306 CGF.EmitStopPoint(&S);
1307 },
1308 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001309 // Emit final copy of the lastprivate variables at the end of loops.
1310 if (HasLastprivateClause) {
1311 CGF.EmitOMPLastprivateClauseFinal(S);
1312 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001313 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001314 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001315 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001316 // Emit: if (PreCond) - end.
1317 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001318 CGF.EmitBranch(ContBlock);
1319 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001320 }
1321 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001322 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001323}
1324
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001325void CodeGenFunction::EmitOMPForOuterLoop(
1326 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1327 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1328 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001329 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001330
1331 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001332 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001333
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001334 assert((Ordered ||
1335 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001336 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001337
1338 // Emit outer loop.
1339 //
1340 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001341 // When schedule(dynamic,chunk_size) is specified, the iterations are
1342 // distributed to threads in the team in chunks as the threads request them.
1343 // Each thread executes a chunk of iterations, then requests another chunk,
1344 // until no chunks remain to be distributed. Each chunk contains chunk_size
1345 // iterations, except for the last chunk to be distributed, which may have
1346 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1347 //
1348 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1349 // to threads in the team in chunks as the executing threads request them.
1350 // Each thread executes a chunk of iterations, then requests another chunk,
1351 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1352 // each chunk is proportional to the number of unassigned iterations divided
1353 // by the number of threads in the team, decreasing to 1. For a chunk_size
1354 // with value k (greater than 1), the size of each chunk is determined in the
1355 // same way, with the restriction that the chunks do not contain fewer than k
1356 // iterations (except for the last chunk to be assigned, which may have fewer
1357 // than k iterations).
1358 //
1359 // When schedule(auto) is specified, the decision regarding scheduling is
1360 // delegated to the compiler and/or runtime system. The programmer gives the
1361 // implementation the freedom to choose any possible mapping of iterations to
1362 // threads in the team.
1363 //
1364 // When schedule(runtime) is specified, the decision regarding scheduling is
1365 // deferred until run time, and the schedule and chunk size are taken from the
1366 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1367 // implementation defined
1368 //
1369 // while(__kmpc_dispatch_next(&LB, &UB)) {
1370 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001371 // while (idx <= UB) { BODY; ++idx;
1372 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1373 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001374 // }
1375 //
1376 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001377 // When schedule(static, chunk_size) is specified, iterations are divided into
1378 // chunks of size chunk_size, and the chunks are assigned to the threads in
1379 // the team in a round-robin fashion in the order of the thread number.
1380 //
1381 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1382 // while (idx <= UB) { BODY; ++idx; } // inner loop
1383 // LB = LB + ST;
1384 // UB = UB + ST;
1385 // }
1386 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001387
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001388 const Expr *IVExpr = S.getIterationVariable();
1389 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1390 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1391
John McCall7f416cc2015-09-08 08:05:57 +00001392 if (DynamicOrOrdered) {
1393 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1394 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1395 IVSize, IVSigned, Ordered, UBVal, Chunk);
1396 } else {
1397 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1398 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1399 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001400
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001401 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1402
1403 // Start the loop with a block that tests the condition.
1404 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1405 EmitBlock(CondBlock);
1406 LoopStack.push(CondBlock);
1407
1408 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001409 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001410 // UB = min(UB, GlobalUB)
1411 EmitIgnoredExpr(S.getEnsureUpperBound());
1412 // IV = LB
1413 EmitIgnoredExpr(S.getInit());
1414 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001415 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001416 } else {
1417 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1418 IL, LB, UB, ST);
1419 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001420
1421 // If there are any cleanups between here and the loop-exit scope,
1422 // create a block to stage a loop exit along.
1423 auto ExitBlock = LoopExit.getBlock();
1424 if (LoopScope.requiresCleanups())
1425 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1426
1427 auto LoopBody = createBasicBlock("omp.dispatch.body");
1428 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1429 if (ExitBlock != LoopExit.getBlock()) {
1430 EmitBlock(ExitBlock);
1431 EmitBranchThroughCleanup(LoopExit);
1432 }
1433 EmitBlock(LoopBody);
1434
Alexander Musman92bdaab2015-03-12 13:37:50 +00001435 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1436 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001437 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001438 EmitIgnoredExpr(S.getInit());
1439
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001440 // Create a block for the increment.
1441 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1442 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1443
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001444 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1445 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001446 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1447 LoopStack.setParallel(!IsMonotonic);
1448 else
1449 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001450
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001451 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001452 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1453 [&S, LoopExit](CodeGenFunction &CGF) {
1454 CGF.EmitOMPLoopBody(S, LoopExit);
1455 CGF.EmitStopPoint(&S);
1456 },
1457 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1458 if (Ordered) {
1459 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1460 CGF, Loc, IVSize, IVSigned);
1461 }
1462 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001463
1464 EmitBlock(Continue.getBlock());
1465 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001466 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001467 // Emit "LB = LB + Stride", "UB = UB + Stride".
1468 EmitIgnoredExpr(S.getNextLowerBound());
1469 EmitIgnoredExpr(S.getNextUpperBound());
1470 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001471
1472 EmitBranch(CondBlock);
1473 LoopStack.pop();
1474 // Emit the fall-through block.
1475 EmitBlock(LoopExit.getBlock());
1476
1477 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001478 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001479 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001480}
1481
Alexander Musmanc6388682014-12-15 07:07:06 +00001482/// \brief Emit a helper variable and return corresponding lvalue.
1483static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1484 const DeclRefExpr *Helper) {
1485 auto VDecl = cast<VarDecl>(Helper->getDecl());
1486 CGF.EmitVarDecl(*VDecl);
1487 return CGF.EmitLValue(Helper);
1488}
1489
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001490namespace {
1491 struct ScheduleKindModifiersTy {
1492 OpenMPScheduleClauseKind Kind;
1493 OpenMPScheduleClauseModifier M1;
1494 OpenMPScheduleClauseModifier M2;
1495 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1496 OpenMPScheduleClauseModifier M1,
1497 OpenMPScheduleClauseModifier M2)
1498 : Kind(Kind), M1(M1), M2(M2) {}
1499 };
1500} // namespace
1501
1502static std::pair<llvm::Value * /*Chunk*/, ScheduleKindModifiersTy>
Alexey Bataev040d5402015-05-12 08:35:28 +00001503emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1504 bool OuterRegion) {
1505 // Detect the loop schedule kind and chunk.
1506 auto ScheduleKind = OMPC_SCHEDULE_unknown;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001507 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1508 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
Alexey Bataev040d5402015-05-12 08:35:28 +00001509 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001510 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001511 ScheduleKind = C->getScheduleKind();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001512 M1 = C->getFirstScheduleModifier();
1513 M2 = C->getSecondScheduleModifier();
Alexey Bataev040d5402015-05-12 08:35:28 +00001514 if (const auto *Ch = C->getChunkSize()) {
1515 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1516 if (OuterRegion) {
1517 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1518 CGF.EmitVarDecl(*ImpVar);
1519 CGF.EmitStoreThroughLValue(
1520 CGF.EmitAnyExpr(Ch),
John McCall7f416cc2015-09-08 08:05:57 +00001521 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1522 ImpVar->getType()));
Alexey Bataev040d5402015-05-12 08:35:28 +00001523 } else {
1524 Ch = ImpRef;
1525 }
1526 }
1527 if (!C->getHelperChunkSize() || !OuterRegion) {
1528 Chunk = CGF.EmitScalarExpr(Ch);
1529 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001530 S.getIterationVariable()->getType(),
1531 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001532 }
1533 }
1534 }
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001535 return std::make_pair(Chunk, ScheduleKindModifiersTy(ScheduleKind, M1, M2));
Alexey Bataev040d5402015-05-12 08:35:28 +00001536}
1537
Alexey Bataev38e89532015-04-16 04:54:05 +00001538bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001539 // Emit the loop iteration variable.
1540 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1541 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1542 EmitVarDecl(*IVDecl);
1543
1544 // Emit the iterations count variable.
1545 // If it is not a variable, Sema decided to calculate iterations count on each
1546 // iteration (e.g., it is foldable into a constant).
1547 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1548 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1549 // Emit calculation of the iterations count.
1550 EmitIgnoredExpr(S.getCalcLastIteration());
1551 }
1552
1553 auto &RT = CGM.getOpenMPRuntime();
1554
Alexey Bataev38e89532015-04-16 04:54:05 +00001555 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001556 // Check pre-condition.
1557 {
1558 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001559 // If the condition constant folds and can be elided, avoid emitting the
1560 // whole loop.
1561 bool CondConstant;
1562 llvm::BasicBlock *ContBlock = nullptr;
1563 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1564 if (!CondConstant)
1565 return false;
1566 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001567 auto *ThenBlock = createBasicBlock("omp.precond.then");
1568 ContBlock = createBasicBlock("omp.precond.end");
1569 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001570 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001571 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001572 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001573 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001574
1575 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001576 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001577 // Emit 'then' code.
1578 {
1579 // Emit helper vars inits.
1580 LValue LB =
1581 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1582 LValue UB =
1583 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1584 LValue ST =
1585 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1586 LValue IL =
1587 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1588
1589 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001590 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1591 // Emit implicit barrier to synchronize threads and avoid data races on
1592 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001593 CGM.getOpenMPRuntime().emitBarrierCall(
1594 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1595 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001596 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001597 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001598 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001599 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001600 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1601 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001602 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001603 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001604
1605 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001606 llvm::Value *Chunk;
1607 OpenMPScheduleClauseKind ScheduleKind;
1608 auto ScheduleInfo =
1609 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1610 Chunk = ScheduleInfo.first;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001611 ScheduleKind = ScheduleInfo.second.Kind;
1612 const OpenMPScheduleClauseModifier M1 = ScheduleInfo.second.M1;
1613 const OpenMPScheduleClauseModifier M2 = ScheduleInfo.second.M2;
Alexander Musmanc6388682014-12-15 07:07:06 +00001614 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1615 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001616 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001617 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1618 // If the static schedule kind is specified or if the ordered clause is
1619 // specified, and if no monotonic modifier is specified, the effect will
1620 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001621 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001622 /* Chunked */ Chunk != nullptr) &&
1623 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001624 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1625 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001626 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1627 // When no chunk_size is specified, the iteration space is divided into
1628 // chunks that are approximately equal in size, and at most one chunk is
1629 // distributed to each thread. Note that the size of the chunks is
1630 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001631 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1632 IVSize, IVSigned, Ordered,
1633 IL.getAddress(), LB.getAddress(),
1634 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001635 auto LoopExit =
1636 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001637 // UB = min(UB, GlobalUB);
1638 EmitIgnoredExpr(S.getEnsureUpperBound());
1639 // IV = LB;
1640 EmitIgnoredExpr(S.getInit());
1641 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001642 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1643 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001644 [&S, LoopExit](CodeGenFunction &CGF) {
1645 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001646 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001647 },
1648 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001649 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001650 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001651 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001652 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001653 const bool IsMonotonic = Ordered ||
1654 ScheduleKind == OMPC_SCHEDULE_static ||
1655 ScheduleKind == OMPC_SCHEDULE_unknown ||
1656 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1657 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001658 // Emit the outer loop, which requests its work chunk [LB..UB] from
1659 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001660 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001661 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1662 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001663 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001664 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001665 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1666 if (HasLastprivateClause)
1667 EmitOMPLastprivateClauseFinal(
1668 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001669 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001670 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1671 EmitOMPSimdFinal(S);
1672 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001673 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001674 if (ContBlock) {
1675 EmitBranch(ContBlock);
1676 EmitBlock(ContBlock, true);
1677 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001678 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001679 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001680}
1681
1682void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001683 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001684 bool HasLastprivates = false;
1685 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1686 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1687 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001688 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1689 S.hasCancel());
Alexander Musmanc6388682014-12-15 07:07:06 +00001690
1691 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001692 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001693 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1694 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001695}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001696
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001697void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1698 LexicalScope Scope(*this, S.getSourceRange());
1699 bool HasLastprivates = false;
1700 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1701 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1702 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001703 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001704
1705 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001706 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001707 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1708 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001709}
1710
Alexey Bataev2df54a02015-03-12 08:53:29 +00001711static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1712 const Twine &Name,
1713 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001714 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001715 if (Init)
1716 CGF.EmitScalarInit(Init, LVal);
1717 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001718}
1719
Alexey Bataev0f34da12015-07-02 04:17:07 +00001720OpenMPDirectiveKind
1721CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001722 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1723 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001724 bool HasLastprivates = false;
1725 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1726 auto &C = CGF.CGM.getContext();
1727 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1728 // Emit helper vars inits.
1729 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1730 CGF.Builder.getInt32(0));
1731 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1732 : CGF.Builder.getInt32(0);
1733 LValue UB =
1734 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1735 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1736 CGF.Builder.getInt32(1));
1737 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1738 CGF.Builder.getInt32(0));
1739 // Loop counter.
1740 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1741 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1742 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1743 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1744 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1745 // Generate condition for loop.
1746 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1747 OK_Ordinary, S.getLocStart(),
1748 /*fpContractable=*/false);
1749 // Increment for loop counter.
1750 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1751 S.getLocStart());
1752 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1753 // Iterate through all sections and emit a switch construct:
1754 // switch (IV) {
1755 // case 0:
1756 // <SectionStmt[0]>;
1757 // break;
1758 // ...
1759 // case <NumSection> - 1:
1760 // <SectionStmt[<NumSection> - 1]>;
1761 // break;
1762 // }
1763 // .omp.sections.exit:
1764 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1765 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1766 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1767 CS == nullptr ? 1 : CS->size());
1768 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001769 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001770 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001771 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1772 CGF.EmitBlock(CaseBB);
1773 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001774 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001775 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001776 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001777 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001778 } else {
1779 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1780 CGF.EmitBlock(CaseBB);
1781 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1782 CGF.EmitStmt(Stmt);
1783 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001784 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001785 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001786 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001787
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001788 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1789 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001790 // Emit implicit barrier to synchronize threads and avoid data races on
1791 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001792 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1793 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1794 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001795 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001796 CGF.EmitOMPPrivateClause(S, LoopScope);
1797 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1798 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1799 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001800
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001801 // Emit static non-chunked loop.
1802 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1803 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1804 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1805 UB.getAddress(), ST.getAddress());
1806 // UB = min(UB, GlobalUB);
1807 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1808 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1809 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1810 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1811 // IV = LB;
1812 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1813 // while (idx <= UB) { BODY; ++idx; }
1814 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1815 [](CodeGenFunction &) {});
1816 // Tell the runtime we are done.
1817 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1818 CGF.EmitOMPReductionClauseFinal(S);
1819
1820 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1821 if (HasLastprivates)
1822 CGF.EmitOMPLastprivateClauseFinal(
1823 S, CGF.Builder.CreateIsNotNull(
1824 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001825 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001826
1827 bool HasCancel = false;
1828 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1829 HasCancel = OSD->hasCancel();
1830 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1831 HasCancel = OPSD->hasCancel();
1832 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1833 HasCancel);
1834 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1835 // clause. Otherwise the barrier will be generated by the codegen for the
1836 // directive.
1837 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001838 // Emit implicit barrier to synchronize threads and avoid data races on
1839 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001840 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1841 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001842 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001843 return OMPD_sections;
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001844}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001845
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001846void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1847 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001848 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001849 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001850 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001851 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001852 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001853}
1854
1855void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001856 LexicalScope Scope(*this, S.getSourceRange());
1857 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1858 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001859 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001860 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1861 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001862}
1863
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001864void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001865 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001866 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001867 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001868 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001869 // Check if there are any 'copyprivate' clauses associated with this
1870 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001871 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001872 // Build a list of copyprivate variables along with helper expressions
1873 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001874 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001875 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001876 DestExprs.append(C->destination_exprs().begin(),
1877 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001878 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001879 AssignmentOps.append(C->assignment_ops().begin(),
1880 C->assignment_ops().end());
1881 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001882 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001883 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001884 bool HasFirstprivates;
1885 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1886 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1887 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001888 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001889 (void)SingleScope.Privatize();
1890
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001891 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001892 };
1893 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001894 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001895 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001896 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1897 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001898 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001899 CopyprivateVars.empty()) {
1900 CGM.getOpenMPRuntime().emitBarrierCall(
1901 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001902 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001903 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001904}
1905
Alexey Bataev8d690652014-12-04 07:23:53 +00001906void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001907 LexicalScope Scope(*this, S.getSourceRange());
1908 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1909 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001910 };
1911 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001912}
1913
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001914void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001915 LexicalScope Scope(*this, S.getSourceRange());
1916 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1917 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001918 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001919 Expr *Hint = nullptr;
1920 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1921 Hint = HintClause->getHint();
1922 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1923 S.getDirectiveName().getAsString(),
1924 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001925}
1926
Alexey Bataev671605e2015-04-13 05:28:11 +00001927void CodeGenFunction::EmitOMPParallelForDirective(
1928 const OMPParallelForDirective &S) {
1929 // Emit directive as a combined directive that consists of two implicit
1930 // directives: 'parallel' with 'for' directive.
1931 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001932 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001933 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1934 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001935 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001936 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001937}
1938
Alexander Musmane4e893b2014-09-23 09:33:00 +00001939void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001940 const OMPParallelForSimdDirective &S) {
1941 // Emit directive as a combined directive that consists of two implicit
1942 // directives: 'parallel' with 'for' directive.
1943 LexicalScope Scope(*this, S.getSourceRange());
1944 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1945 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1946 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001947 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001948 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001949}
1950
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001951void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001952 const OMPParallelSectionsDirective &S) {
1953 // Emit directive as a combined directive that consists of two implicit
1954 // directives: 'parallel' with 'sections' directive.
1955 LexicalScope Scope(*this, S.getSourceRange());
1956 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001957 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001958 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001959 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001960}
1961
Alexey Bataev62b63b12015-03-10 07:28:44 +00001962void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1963 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001964 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001965 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1966 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1967 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001968 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001969 // The first function argument for tasks is a thread id, the second one is a
1970 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001971 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1972 // Get list of private variables.
1973 llvm::SmallVector<const Expr *, 8> PrivateVars;
1974 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001975 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001976 auto IRef = C->varlist_begin();
1977 for (auto *IInit : C->private_copies()) {
1978 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1979 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1980 PrivateVars.push_back(*IRef);
1981 PrivateCopies.push_back(IInit);
1982 }
1983 ++IRef;
1984 }
1985 }
1986 EmittedAsPrivate.clear();
1987 // Get list of firstprivate variables.
1988 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1989 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1990 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001991 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001992 auto IRef = C->varlist_begin();
1993 auto IElemInitRef = C->inits().begin();
1994 for (auto *IInit : C->private_copies()) {
1995 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1996 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1997 FirstprivateVars.push_back(*IRef);
1998 FirstprivateCopies.push_back(IInit);
1999 FirstprivateInits.push_back(*IElemInitRef);
2000 }
2001 ++IRef, ++IElemInitRef;
2002 }
2003 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002004 // Build list of dependences.
2005 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2006 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002007 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002008 for (auto *IRef : C->varlists()) {
2009 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2010 }
2011 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002012 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2013 CodeGenFunction &CGF) {
2014 // Set proper addresses for generated private copies.
2015 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2016 OMPPrivateScope Scope(CGF);
2017 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002018 auto *CopyFn = CGF.Builder.CreateLoad(
2019 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2020 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2021 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002022 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002023 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002024 PrivatePtrs;
2025 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2026 CallArgs.push_back(PrivatesPtr);
2027 for (auto *E : PrivateVars) {
2028 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002029 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002030 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2031 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002032 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002033 }
2034 for (auto *E : FirstprivateVars) {
2035 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002036 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002037 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2038 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002039 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002040 }
2041 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2042 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002043 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2044 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002045 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2046 }
2047 }
2048 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002049 if (*PartId) {
2050 // TODO: emit code for untied tasks.
2051 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002052 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002053 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002054 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2055 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002056 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002057 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002058 // Check if the task is final
2059 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002060 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002061 // If the condition constant folds and can be elided, try to avoid emitting
2062 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002063 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002064 bool CondConstant;
2065 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2066 Final.setInt(CondConstant);
2067 else
2068 Final.setPointer(EvaluateExprAsBool(Cond));
2069 } else {
2070 // By default the task is not final.
2071 Final.setInt(/*IntVal=*/false);
2072 }
2073 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002074 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002075 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2076 if (C->getNameModifier() == OMPD_unknown ||
2077 C->getNameModifier() == OMPD_task) {
2078 IfCond = C->getCondition();
2079 break;
2080 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002081 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002082 CGM.getOpenMPRuntime().emitTaskCall(
2083 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002084 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002085 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002086}
2087
Alexey Bataev9f797f32015-02-05 05:57:51 +00002088void CodeGenFunction::EmitOMPTaskyieldDirective(
2089 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002090 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002091}
2092
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002093void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002094 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002095}
2096
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002097void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2098 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002099}
2100
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002101void CodeGenFunction::EmitOMPTaskgroupDirective(
2102 const OMPTaskgroupDirective &S) {
2103 LexicalScope Scope(*this, S.getSourceRange());
2104 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2105 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002106 };
2107 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2108}
2109
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002110void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002111 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002112 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002113 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2114 FlushClause->varlist_end());
2115 }
2116 return llvm::None;
2117 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002118}
2119
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002120void CodeGenFunction::EmitOMPDistributeDirective(
2121 const OMPDistributeDirective &S) {
2122 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2123}
2124
Alexey Bataev5f600d62015-09-29 03:48:57 +00002125static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2126 const CapturedStmt *S) {
2127 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2128 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2129 CGF.CapturedStmtInfo = &CapStmtInfo;
2130 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2131 Fn->addFnAttr(llvm::Attribute::NoInline);
2132 return Fn;
2133}
2134
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002135void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002136 if (!S.getAssociatedStmt())
2137 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002138 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev5f600d62015-09-29 03:48:57 +00002139 auto *C = S.getSingleClause<OMPSIMDClause>();
2140 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2141 if (C) {
2142 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2143 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2144 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2145 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2146 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2147 } else {
2148 CGF.EmitStmt(
2149 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2150 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002151 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002152 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002153}
2154
Alexey Bataevb57056f2015-01-22 06:17:56 +00002155static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002156 QualType SrcType, QualType DestType,
2157 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002158 assert(CGF.hasScalarEvaluationKind(DestType) &&
2159 "DestType must have scalar evaluation kind.");
2160 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2161 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002162 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2163 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002164 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002165 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002166}
2167
2168static CodeGenFunction::ComplexPairTy
2169convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002170 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002171 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2172 "DestType must have complex evaluation kind.");
2173 CodeGenFunction::ComplexPairTy ComplexVal;
2174 if (Val.isScalar()) {
2175 // Convert the input element to the element type of the complex.
2176 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002177 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2178 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002179 ComplexVal = CodeGenFunction::ComplexPairTy(
2180 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2181 } else {
2182 assert(Val.isComplex() && "Must be a scalar or complex.");
2183 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2184 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2185 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002186 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002187 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002188 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002189 }
2190 return ComplexVal;
2191}
2192
Alexey Bataev5e018f92015-04-23 06:35:10 +00002193static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2194 LValue LVal, RValue RVal) {
2195 if (LVal.isGlobalReg()) {
2196 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2197 } else {
2198 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2199 : llvm::Monotonic,
2200 LVal.isVolatile(), /*IsInit=*/false);
2201 }
2202}
2203
Alexey Bataev8524d152016-01-21 12:35:58 +00002204void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2205 QualType RValTy, SourceLocation Loc) {
2206 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002207 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002208 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2209 *this, RVal, RValTy, LVal.getType(), Loc)),
2210 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002211 break;
2212 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002213 EmitStoreOfComplex(
2214 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002215 /*isInit=*/false);
2216 break;
2217 case TEK_Aggregate:
2218 llvm_unreachable("Must be a scalar or complex.");
2219 }
2220}
2221
Alexey Bataevb57056f2015-01-22 06:17:56 +00002222static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2223 const Expr *X, const Expr *V,
2224 SourceLocation Loc) {
2225 // v = x;
2226 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2227 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2228 LValue XLValue = CGF.EmitLValue(X);
2229 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002230 RValue Res = XLValue.isGlobalReg()
2231 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2232 : CGF.EmitAtomicLoad(XLValue, Loc,
2233 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002234 : llvm::Monotonic,
2235 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002236 // OpenMP, 2.12.6, atomic Construct
2237 // Any atomic construct with a seq_cst clause forces the atomically
2238 // performed operation to include an implicit flush operation without a
2239 // list.
2240 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002241 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002242 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002243}
2244
Alexey Bataevb8329262015-02-27 06:33:30 +00002245static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2246 const Expr *X, const Expr *E,
2247 SourceLocation Loc) {
2248 // x = expr;
2249 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002250 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002251 // OpenMP, 2.12.6, atomic Construct
2252 // Any atomic construct with a seq_cst clause forces the atomically
2253 // performed operation to include an implicit flush operation without a
2254 // list.
2255 if (IsSeqCst)
2256 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2257}
2258
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002259static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2260 RValue Update,
2261 BinaryOperatorKind BO,
2262 llvm::AtomicOrdering AO,
2263 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002264 auto &Context = CGF.CGM.getContext();
2265 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002266 // expression is simple and atomic is allowed for the given type for the
2267 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002268 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002269 !Update.getScalarVal()->getType()->isIntegerTy() ||
2270 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2271 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002272 X.getAddress().getElementType())) ||
2273 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002274 !Context.getTargetInfo().hasBuiltinAtomic(
2275 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002276 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002277
2278 llvm::AtomicRMWInst::BinOp RMWOp;
2279 switch (BO) {
2280 case BO_Add:
2281 RMWOp = llvm::AtomicRMWInst::Add;
2282 break;
2283 case BO_Sub:
2284 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002285 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002286 RMWOp = llvm::AtomicRMWInst::Sub;
2287 break;
2288 case BO_And:
2289 RMWOp = llvm::AtomicRMWInst::And;
2290 break;
2291 case BO_Or:
2292 RMWOp = llvm::AtomicRMWInst::Or;
2293 break;
2294 case BO_Xor:
2295 RMWOp = llvm::AtomicRMWInst::Xor;
2296 break;
2297 case BO_LT:
2298 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2299 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2300 : llvm::AtomicRMWInst::Max)
2301 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2302 : llvm::AtomicRMWInst::UMax);
2303 break;
2304 case BO_GT:
2305 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2306 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2307 : llvm::AtomicRMWInst::Min)
2308 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2309 : llvm::AtomicRMWInst::UMin);
2310 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002311 case BO_Assign:
2312 RMWOp = llvm::AtomicRMWInst::Xchg;
2313 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002314 case BO_Mul:
2315 case BO_Div:
2316 case BO_Rem:
2317 case BO_Shl:
2318 case BO_Shr:
2319 case BO_LAnd:
2320 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002321 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002322 case BO_PtrMemD:
2323 case BO_PtrMemI:
2324 case BO_LE:
2325 case BO_GE:
2326 case BO_EQ:
2327 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002328 case BO_AddAssign:
2329 case BO_SubAssign:
2330 case BO_AndAssign:
2331 case BO_OrAssign:
2332 case BO_XorAssign:
2333 case BO_MulAssign:
2334 case BO_DivAssign:
2335 case BO_RemAssign:
2336 case BO_ShlAssign:
2337 case BO_ShrAssign:
2338 case BO_Comma:
2339 llvm_unreachable("Unsupported atomic update operation");
2340 }
2341 auto *UpdateVal = Update.getScalarVal();
2342 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2343 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002344 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002345 X.getType()->hasSignedIntegerRepresentation());
2346 }
John McCall7f416cc2015-09-08 08:05:57 +00002347 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002348 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002349}
2350
Alexey Bataev5e018f92015-04-23 06:35:10 +00002351std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002352 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2353 llvm::AtomicOrdering AO, SourceLocation Loc,
2354 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2355 // Update expressions are allowed to have the following forms:
2356 // x binop= expr; -> xrval + expr;
2357 // x++, ++x -> xrval + 1;
2358 // x--, --x -> xrval - 1;
2359 // x = x binop expr; -> xrval binop expr
2360 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002361 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2362 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002363 if (X.isGlobalReg()) {
2364 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2365 // 'xrval'.
2366 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2367 } else {
2368 // Perform compare-and-swap procedure.
2369 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002370 }
2371 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002372 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002373}
2374
2375static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2376 const Expr *X, const Expr *E,
2377 const Expr *UE, bool IsXLHSInRHSPart,
2378 SourceLocation Loc) {
2379 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2380 "Update expr in 'atomic update' must be a binary operator.");
2381 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2382 // Update expressions are allowed to have the following forms:
2383 // x binop= expr; -> xrval + expr;
2384 // x++, ++x -> xrval + 1;
2385 // x--, --x -> xrval - 1;
2386 // x = x binop expr; -> xrval binop expr
2387 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002388 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002389 LValue XLValue = CGF.EmitLValue(X);
2390 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002391 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002392 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2393 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2394 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2395 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2396 auto Gen =
2397 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2398 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2399 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2400 return CGF.EmitAnyExpr(UE);
2401 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002402 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2403 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2404 // OpenMP, 2.12.6, atomic Construct
2405 // Any atomic construct with a seq_cst clause forces the atomically
2406 // performed operation to include an implicit flush operation without a
2407 // list.
2408 if (IsSeqCst)
2409 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2410}
2411
2412static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002413 QualType SourceType, QualType ResType,
2414 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002415 switch (CGF.getEvaluationKind(ResType)) {
2416 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002417 return RValue::get(
2418 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002419 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002420 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002421 return RValue::getComplex(Res.first, Res.second);
2422 }
2423 case TEK_Aggregate:
2424 break;
2425 }
2426 llvm_unreachable("Must be a scalar or complex.");
2427}
2428
2429static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2430 bool IsPostfixUpdate, const Expr *V,
2431 const Expr *X, const Expr *E,
2432 const Expr *UE, bool IsXLHSInRHSPart,
2433 SourceLocation Loc) {
2434 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2435 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2436 RValue NewVVal;
2437 LValue VLValue = CGF.EmitLValue(V);
2438 LValue XLValue = CGF.EmitLValue(X);
2439 RValue ExprRValue = CGF.EmitAnyExpr(E);
2440 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2441 QualType NewVValType;
2442 if (UE) {
2443 // 'x' is updated with some additional value.
2444 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2445 "Update expr in 'atomic capture' must be a binary operator.");
2446 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2447 // Update expressions are allowed to have the following forms:
2448 // x binop= expr; -> xrval + expr;
2449 // x++, ++x -> xrval + 1;
2450 // x--, --x -> xrval - 1;
2451 // x = x binop expr; -> xrval binop expr
2452 // x = expr Op x; - > expr binop xrval;
2453 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2454 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2455 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2456 NewVValType = XRValExpr->getType();
2457 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2458 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2459 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2460 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2461 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2462 RValue Res = CGF.EmitAnyExpr(UE);
2463 NewVVal = IsPostfixUpdate ? XRValue : Res;
2464 return Res;
2465 };
2466 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2467 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2468 if (Res.first) {
2469 // 'atomicrmw' instruction was generated.
2470 if (IsPostfixUpdate) {
2471 // Use old value from 'atomicrmw'.
2472 NewVVal = Res.second;
2473 } else {
2474 // 'atomicrmw' does not provide new value, so evaluate it using old
2475 // value of 'x'.
2476 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2477 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2478 NewVVal = CGF.EmitAnyExpr(UE);
2479 }
2480 }
2481 } else {
2482 // 'x' is simply rewritten with some 'expr'.
2483 NewVValType = X->getType().getNonReferenceType();
2484 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002485 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002486 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2487 NewVVal = XRValue;
2488 return ExprRValue;
2489 };
2490 // Try to perform atomicrmw xchg, otherwise simple exchange.
2491 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2492 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2493 Loc, Gen);
2494 if (Res.first) {
2495 // 'atomicrmw' instruction was generated.
2496 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2497 }
2498 }
2499 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002500 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002501 // OpenMP, 2.12.6, atomic Construct
2502 // Any atomic construct with a seq_cst clause forces the atomically
2503 // performed operation to include an implicit flush operation without a
2504 // list.
2505 if (IsSeqCst)
2506 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2507}
2508
Alexey Bataevb57056f2015-01-22 06:17:56 +00002509static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002510 bool IsSeqCst, bool IsPostfixUpdate,
2511 const Expr *X, const Expr *V, const Expr *E,
2512 const Expr *UE, bool IsXLHSInRHSPart,
2513 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002514 switch (Kind) {
2515 case OMPC_read:
2516 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2517 break;
2518 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002519 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2520 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002521 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002522 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002523 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2524 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002525 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002526 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2527 IsXLHSInRHSPart, Loc);
2528 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002529 case OMPC_if:
2530 case OMPC_final:
2531 case OMPC_num_threads:
2532 case OMPC_private:
2533 case OMPC_firstprivate:
2534 case OMPC_lastprivate:
2535 case OMPC_reduction:
2536 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002537 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002538 case OMPC_collapse:
2539 case OMPC_default:
2540 case OMPC_seq_cst:
2541 case OMPC_shared:
2542 case OMPC_linear:
2543 case OMPC_aligned:
2544 case OMPC_copyin:
2545 case OMPC_copyprivate:
2546 case OMPC_flush:
2547 case OMPC_proc_bind:
2548 case OMPC_schedule:
2549 case OMPC_ordered:
2550 case OMPC_nowait:
2551 case OMPC_untied:
2552 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002553 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002554 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002555 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002556 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002557 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002558 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002559 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002560 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002561 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002562 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002563 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002564 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002565 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002566 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002567 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002568 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2569 }
2570}
2571
2572void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002573 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002574 OpenMPClauseKind Kind = OMPC_unknown;
2575 for (auto *C : S.clauses()) {
2576 // Find first clause (skip seq_cst clause, if it is first).
2577 if (C->getClauseKind() != OMPC_seq_cst) {
2578 Kind = C->getClauseKind();
2579 break;
2580 }
2581 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002582
2583 const auto *CS =
2584 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002585 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002586 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002587 }
2588 // Processing for statements under 'atomic capture'.
2589 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2590 for (const auto *C : Compound->body()) {
2591 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2592 enterFullExpression(EWC);
2593 }
2594 }
2595 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002596
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002597 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev33c56402015-12-14 09:26:19 +00002598 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2599 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002600 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2601 S.getV(), S.getExpr(), S.getUpdateExpr(),
2602 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002603 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002604 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002605}
2606
Samuel Antaobed3c462015-10-02 16:14:20 +00002607void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
2608 LexicalScope Scope(*this, S.getSourceRange());
2609 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2610
2611 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002612 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002613
Samuel Antaoee8fb302016-01-06 13:42:12 +00002614 llvm::Function *Fn = nullptr;
2615 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002616
2617 // Check if we have any if clause associated with the directive.
2618 const Expr *IfCond = nullptr;
2619
2620 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2621 IfCond = C->getCondition();
2622 }
2623
2624 // Check if we have any device clause associated with the directive.
2625 const Expr *Device = nullptr;
2626 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2627 Device = C->getDevice();
2628 }
2629
Samuel Antaoee8fb302016-01-06 13:42:12 +00002630 // Check if we have an if clause whose conditional always evaluates to false
2631 // or if we do not have any targets specified. If so the target region is not
2632 // an offload entry point.
2633 bool IsOffloadEntry = true;
2634 if (IfCond) {
2635 bool Val;
2636 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2637 IsOffloadEntry = false;
2638 }
2639 if (CGM.getLangOpts().OMPTargetTriples.empty())
2640 IsOffloadEntry = false;
2641
2642 assert(CurFuncDecl && "No parent declaration for target region!");
2643 StringRef ParentName;
2644 // In case we have Ctors/Dtors we use the complete type variant to produce
2645 // the mangling of the device outlined kernel.
2646 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2647 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2648 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2649 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2650 else
2651 ParentName =
2652 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2653
2654 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2655 IsOffloadEntry);
2656
2657 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002658 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002659}
2660
Alexey Bataev13314bf2014-10-09 04:18:56 +00002661void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2662 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2663}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002664
2665void CodeGenFunction::EmitOMPCancellationPointDirective(
2666 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002667 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2668 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002669}
2670
Alexey Bataev80909872015-07-02 11:25:17 +00002671void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002672 const Expr *IfCond = nullptr;
2673 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2674 if (C->getNameModifier() == OMPD_unknown ||
2675 C->getNameModifier() == OMPD_cancel) {
2676 IfCond = C->getCondition();
2677 break;
2678 }
2679 }
2680 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002681 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002682}
2683
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002684CodeGenFunction::JumpDest
2685CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2686 if (Kind == OMPD_parallel || Kind == OMPD_task)
2687 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002688 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002689 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002690 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002691}
Michael Wong65f367f2015-07-21 13:44:28 +00002692
2693// Generate the instructions for '#pragma omp target data' directive.
2694void CodeGenFunction::EmitOMPTargetDataDirective(
2695 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002696 // emit the code inside the construct for now
2697 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002698 CGM.getOpenMPRuntime().emitInlinedDirective(
2699 *this, OMPD_target_data,
2700 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002701}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002702
Samuel Antaodf67fc42016-01-19 19:15:56 +00002703void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2704 const OMPTargetEnterDataDirective &S) {
2705 // TODO: codegen for target enter data.
2706}
2707
Samuel Antao72590762016-01-19 20:04:50 +00002708void CodeGenFunction::EmitOMPTargetExitDataDirective(
2709 const OMPTargetExitDataDirective &S) {
2710 // TODO: codegen for target exit data.
2711}
2712
Alexey Bataev49f6e782015-12-01 04:18:41 +00002713void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2714 // emit the code inside the construct for now
2715 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2716 CGM.getOpenMPRuntime().emitInlinedDirective(
2717 *this, OMPD_taskloop,
2718 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2719}
2720
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002721void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2722 const OMPTaskLoopSimdDirective &S) {
2723 // emit the code inside the construct for now
2724 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2725 CGM.getOpenMPRuntime().emitInlinedDirective(
2726 *this, OMPD_taskloop_simd,
2727 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2728}
2729