blob: a4bc354ddb697cd59f811d59776127bff10c81f6 [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
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
21using namespace clang;
22using namespace CodeGen;
23
Alexey Bataev3392d762016-02-16 11:18:12 +000024namespace {
25/// Lexical scope for OpenMP executable constructs, that handles correct codegen
26/// for captured expressions.
27class OMPLexicalScope {
28 CodeGenFunction::LexicalScope Scope;
29 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
30 for (const auto *C : S.clauses()) {
31 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
32 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
33 for (const auto *I : PreInit->decls())
34 CGF.EmitVarDecl(cast<VarDecl>(*I));
35 }
36 }
37 }
38 }
39
40 class PostUpdateCleanup final : public EHScopeStack::Cleanup {
41 const OMPExecutableDirective &S;
42
43 public:
44 PostUpdateCleanup(const OMPExecutableDirective &S) : S(S) {}
45
46 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
47 if (!CGF.HaveInsertPoint())
48 return;
49 (void)S;
50 // TODO: add cleanups for clauses that require post update.
51 }
52 };
53
54public:
55 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
56 : Scope(CGF, S.getSourceRange()) {
57 emitPreInitStmt(CGF, S);
58 CGF.EHStack.pushCleanup<PostUpdateCleanup>(NormalAndEHCleanup, S);
59 }
60};
61} // namespace
62
Alexey Bataev1189bd02016-01-26 12:20:39 +000063llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
64 auto &C = getContext();
65 llvm::Value *Size = nullptr;
66 auto SizeInChars = C.getTypeSizeInChars(Ty);
67 if (SizeInChars.isZero()) {
68 // getTypeSizeInChars() returns 0 for a VLA.
69 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
70 llvm::Value *ArraySize;
71 std::tie(ArraySize, Ty) = getVLASize(VAT);
72 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
73 }
74 SizeInChars = C.getTypeSizeInChars(Ty);
75 if (SizeInChars.isZero())
76 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
77 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
78 } else
79 Size = CGM.getSize(SizeInChars);
80 return Size;
81}
82
Alexey Bataev2377fe92015-09-10 08:12:02 +000083void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000084 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000085 const RecordDecl *RD = S.getCapturedRecordDecl();
86 auto CurField = RD->field_begin();
87 auto CurCap = S.captures().begin();
88 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
89 E = S.capture_init_end();
90 I != E; ++I, ++CurField, ++CurCap) {
91 if (CurField->hasCapturedVLAType()) {
92 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000093 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000094 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000095 } else if (CurCap->capturesThis())
96 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000097 else if (CurCap->capturesVariableByCopy())
98 CapturedVars.push_back(
99 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
100 else {
101 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000102 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000103 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000104 }
105}
106
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000107static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
108 StringRef Name, LValue AddrLV,
109 bool isReferenceType = false) {
110 ASTContext &Ctx = CGF.getContext();
111
112 auto *CastedPtr = CGF.EmitScalarConversion(
113 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
114 Ctx.getPointerType(DstType), SourceLocation());
115 auto TmpAddr =
116 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
117 .getAddress();
118
119 // If we are dealing with references we need to return the address of the
120 // reference instead of the reference of the value.
121 if (isReferenceType) {
122 QualType RefType = Ctx.getLValueReferenceType(DstType);
123 auto *RefVal = TmpAddr.getPointer();
124 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
125 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
126 CGF.EmitScalarInit(RefVal, TmpLVal);
127 }
128
129 return TmpAddr;
130}
131
Alexey Bataev2377fe92015-09-10 08:12:02 +0000132llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000133CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000134 assert(
135 CapturedStmtInfo &&
136 "CapturedStmtInfo should be set when generating the captured function");
137 const CapturedDecl *CD = S.getCapturedDecl();
138 const RecordDecl *RD = S.getCapturedRecordDecl();
139 assert(CD->hasBody() && "missing CapturedDecl body");
140
141 // Build the argument list.
142 ASTContext &Ctx = CGM.getContext();
143 FunctionArgList Args;
144 Args.append(CD->param_begin(),
145 std::next(CD->param_begin(), CD->getContextParamPosition()));
146 auto I = S.captures().begin();
147 for (auto *FD : RD->fields()) {
148 QualType ArgType = FD->getType();
149 IdentifierInfo *II = nullptr;
150 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000151
152 // If this is a capture by copy and the type is not a pointer, the outlined
153 // function argument type should be uintptr and the value properly casted to
154 // uintptr. This is necessary given that the runtime library is only able to
155 // deal with pointers. We can pass in the same way the VLA type sizes to the
156 // outlined function.
157 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
158 I->capturesVariableArrayType())
159 ArgType = Ctx.getUIntPtrType();
160
161 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000162 CapVar = I->getCapturedVar();
163 II = CapVar->getIdentifier();
164 } else if (I->capturesThis())
165 II = &getContext().Idents.get("this");
166 else {
167 assert(I->capturesVariableArrayType());
168 II = &getContext().Idents.get("vla");
169 }
170 if (ArgType->isVariablyModifiedType())
171 ArgType = getContext().getVariableArrayDecayedType(ArgType);
172 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
173 FD->getLocation(), II, ArgType));
174 ++I;
175 }
176 Args.append(
177 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
178 CD->param_end());
179
180 // Create the function declaration.
181 FunctionType::ExtInfo ExtInfo;
182 const CGFunctionInfo &FuncInfo =
183 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
184 /*IsVariadic=*/false);
185 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
186
187 llvm::Function *F = llvm::Function::Create(
188 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
189 CapturedStmtInfo->getHelperName(), &CGM.getModule());
190 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
191 if (CD->isNothrow())
192 F->addFnAttr(llvm::Attribute::NoUnwind);
193
194 // Generate the function.
195 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
196 CD->getBody()->getLocStart());
197 unsigned Cnt = CD->getContextParamPosition();
198 I = S.captures().begin();
199 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000200 // If we are capturing a pointer by copy we don't need to do anything, just
201 // use the value that we get from the arguments.
202 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
203 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
204 ++Cnt, ++I;
205 continue;
206 }
207
Alexey Bataev2377fe92015-09-10 08:12:02 +0000208 LValue ArgLVal =
209 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
210 AlignmentSource::Decl);
211 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000212 LValue CastedArgLVal =
213 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
214 Args[Cnt]->getName(), ArgLVal),
215 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000216 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000217 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000218 auto VAT = FD->getCapturedVLAType();
219 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
220 } else if (I->capturesVariable()) {
221 auto *Var = I->getCapturedVar();
222 QualType VarTy = Var->getType();
223 Address ArgAddr = ArgLVal.getAddress();
224 if (!VarTy->isReferenceType()) {
225 ArgAddr = EmitLoadOfReference(
226 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
227 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000228 setAddrOfLocalVar(
229 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000230 } else if (I->capturesVariableByCopy()) {
231 assert(!FD->getType()->isAnyPointerType() &&
232 "Not expecting a captured pointer.");
233 auto *Var = I->getCapturedVar();
234 QualType VarTy = Var->getType();
235 setAddrOfLocalVar(I->getCapturedVar(),
236 castValueFromUintptr(*this, FD->getType(),
237 Args[Cnt]->getName(), ArgLVal,
238 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000239 } else {
240 // If 'this' is captured, load it into CXXThisValue.
241 assert(I->capturesThis());
242 CXXThisValue =
243 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
244 }
245 ++Cnt, ++I;
246 }
247
Serge Pavlov3a561452015-12-06 14:32:39 +0000248 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000249 CapturedStmtInfo->EmitBody(*this, CD->getBody());
250 FinishFunction(CD->getBodyRBrace());
251
252 return F;
253}
254
Alexey Bataev9959db52014-05-06 10:08:46 +0000255//===----------------------------------------------------------------------===//
256// OpenMP Directive Emission
257//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000258void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000259 Address DestAddr, Address SrcAddr, QualType OriginalType,
260 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000261 // Perform element-by-element initialization.
262 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000263
264 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000265 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000266 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
267 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
268
269 auto SrcBegin = SrcAddr.getPointer();
270 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000271 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000272 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
273 // The basic structure here is a while-do loop.
274 auto BodyBB = createBasicBlock("omp.arraycpy.body");
275 auto DoneBB = createBasicBlock("omp.arraycpy.done");
276 auto IsEmpty =
277 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
278 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000279
Alexey Bataev420d45b2015-04-14 05:11:24 +0000280 // Enter the loop body, making that address the current address.
281 auto EntryBB = Builder.GetInsertBlock();
282 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000283
284 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
285
286 llvm::PHINode *SrcElementPHI =
287 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
288 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
289 Address SrcElementCurrent =
290 Address(SrcElementPHI,
291 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
292
293 llvm::PHINode *DestElementPHI =
294 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
295 DestElementPHI->addIncoming(DestBegin, EntryBB);
296 Address DestElementCurrent =
297 Address(DestElementPHI,
298 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000299
Alexey Bataev420d45b2015-04-14 05:11:24 +0000300 // Emit copy.
301 CopyGen(DestElementCurrent, SrcElementCurrent);
302
303 // Shift the address forward by one element.
304 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000305 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000306 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000307 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000308 // Check whether we've reached the end.
309 auto Done =
310 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
311 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000312 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
313 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000314
315 // Done.
316 EmitBlock(DoneBB, /*IsFinished=*/true);
317}
318
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000319/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000320/// \param DestAddr Address of the array.
321/// \param Type Type of array.
322/// \param Init Initial expression of array.
323static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
324 QualType Type, const Expr *Init) {
325 // Perform element-by-element initialization.
326 QualType ElementTy;
327
328 // Drill down to the base element type on both arrays.
329 auto ArrayTy = Type->getAsArrayTypeUnsafe();
330 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
331 DestAddr =
332 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
333
334 auto DestBegin = DestAddr.getPointer();
335 // Cast from pointer to array type to pointer to single element.
336 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
337 // The basic structure here is a while-do loop.
338 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
339 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
340 auto IsEmpty =
341 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
342 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
343
344 // Enter the loop body, making that address the current address.
345 auto EntryBB = CGF.Builder.GetInsertBlock();
346 CGF.EmitBlock(BodyBB);
347
348 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
349
350 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
351 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
352 DestElementPHI->addIncoming(DestBegin, EntryBB);
353 Address DestElementCurrent =
354 Address(DestElementPHI,
355 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
356
357 // Emit copy.
358 {
359 CodeGenFunction::RunCleanupsScope InitScope(CGF);
360 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
361 /*IsInitializer=*/false);
362 }
363
364 // Shift the address forward by one element.
365 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
366 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
367 // Check whether we've reached the end.
368 auto Done =
369 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
370 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
371 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
372
373 // Done.
374 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
375}
376
John McCall7f416cc2015-09-08 08:05:57 +0000377void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
378 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000379 const VarDecl *SrcVD, const Expr *Copy) {
380 if (OriginalType->isArrayType()) {
381 auto *BO = dyn_cast<BinaryOperator>(Copy);
382 if (BO && BO->getOpcode() == BO_Assign) {
383 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000384 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000385 } else {
386 // For arrays with complex element types perform element by element
387 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000388 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000389 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000390 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000391 // Working with the single array element, so have to remap
392 // destination and source variables to corresponding array
393 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000394 CodeGenFunction::OMPPrivateScope Remap(*this);
395 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000396 return DestElement;
397 });
398 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000399 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000400 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000401 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000402 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000403 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000404 } else {
405 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000406 CodeGenFunction::OMPPrivateScope Remap(*this);
407 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
408 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000409 (void)Remap.Privatize();
410 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000411 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000412 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000413}
414
Alexey Bataev69c62a92015-04-15 04:52:20 +0000415bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
416 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000417 if (!HaveInsertPoint())
418 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000419 bool FirstprivateIsLastprivate = false;
420 llvm::DenseSet<const VarDecl *> Lastprivates;
421 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
422 for (const auto *D : C->varlists())
423 Lastprivates.insert(
424 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
425 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000426 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000427 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000428 auto IRef = C->varlist_begin();
429 auto InitsRef = C->inits().begin();
430 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000431 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000432 FirstprivateIsLastprivate =
433 FirstprivateIsLastprivate ||
434 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
435 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000436 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
437 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
438 bool IsRegistered;
439 DeclRefExpr DRE(
440 const_cast<VarDecl *>(OrigVD),
441 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
442 OrigVD) != nullptr,
443 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000444 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000445 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000446 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000447 // Emit VarDecl with copy init for arrays.
448 // Get the address of the original variable captured in current
449 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000450 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000451 auto Emission = EmitAutoVarAlloca(*VD);
452 auto *Init = VD->getInit();
453 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
454 // Perform simple memcpy.
455 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000456 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000457 } else {
458 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000459 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000460 [this, VDInit, Init](Address DestElement,
461 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000462 // Clean up any temporaries needed by the initialization.
463 RunCleanupsScope InitScope(*this);
464 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000465 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000466 EmitAnyExprToMem(Init, DestElement,
467 Init->getType().getQualifiers(),
468 /*IsInitializer*/ false);
469 LocalDeclMap.erase(VDInit);
470 });
471 }
472 EmitAutoVarCleanups(Emission);
473 return Emission.getAllocatedAddress();
474 });
475 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000476 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 // Emit private VarDecl with copy init.
478 // Remap temp VDInit variable to the address of the original
479 // variable
480 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000481 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000482 EmitDecl(*VD);
483 LocalDeclMap.erase(VDInit);
484 return GetAddrOfLocalVar(VD);
485 });
486 }
487 assert(IsRegistered &&
488 "firstprivate var already registered as private");
489 // Silence the warning about unused variable.
490 (void)IsRegistered;
491 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000492 ++IRef, ++InitsRef;
493 }
494 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000495 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000496}
497
Alexey Bataev03b340a2014-10-21 03:16:40 +0000498void CodeGenFunction::EmitOMPPrivateClause(
499 const OMPExecutableDirective &D,
500 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000501 if (!HaveInsertPoint())
502 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000503 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000504 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000505 auto IRef = C->varlist_begin();
506 for (auto IInit : C->private_copies()) {
507 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000508 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
509 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
510 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000511 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000512 // Emit private VarDecl with copy init.
513 EmitDecl(*VD);
514 return GetAddrOfLocalVar(VD);
515 });
516 assert(IsRegistered && "private var already registered as private");
517 // Silence the warning about unused variable.
518 (void)IsRegistered;
519 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000520 ++IRef;
521 }
522 }
523}
524
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000525bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000526 if (!HaveInsertPoint())
527 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 // threadprivate_var1 = master_threadprivate_var1;
529 // operator=(threadprivate_var2, master_threadprivate_var2);
530 // ...
531 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000532 llvm::DenseSet<const VarDecl *> CopiedVars;
533 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000534 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000535 auto IRef = C->varlist_begin();
536 auto ISrcRef = C->source_exprs().begin();
537 auto IDestRef = C->destination_exprs().begin();
538 for (auto *AssignOp : C->assignment_ops()) {
539 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000540 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000541 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000542 // Get the address of the master variable. If we are emitting code with
543 // TLS support, the address is passed from the master as field in the
544 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000545 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000546 if (getLangOpts().OpenMPUseTLS &&
547 getContext().getTargetInfo().isTLSSupported()) {
548 assert(CapturedStmtInfo->lookup(VD) &&
549 "Copyin threadprivates should have been captured!");
550 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
551 VK_LValue, (*IRef)->getExprLoc());
552 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000553 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000554 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000555 MasterAddr =
556 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
557 : CGM.GetAddrOfGlobal(VD),
558 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000559 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000560 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000561 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000562 if (CopiedVars.size() == 1) {
563 // At first check if current thread is a master thread. If it is, no
564 // need to copy data.
565 CopyBegin = createBasicBlock("copyin.not.master");
566 CopyEnd = createBasicBlock("copyin.not.master.end");
567 Builder.CreateCondBr(
568 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000569 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
570 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000571 CopyBegin, CopyEnd);
572 EmitBlock(CopyBegin);
573 }
574 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
575 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000576 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000577 }
578 ++IRef;
579 ++ISrcRef;
580 ++IDestRef;
581 }
582 }
583 if (CopyEnd) {
584 // Exit out of copying procedure for non-master thread.
585 EmitBlock(CopyEnd, /*IsFinished=*/true);
586 return true;
587 }
588 return false;
589}
590
Alexey Bataev38e89532015-04-16 04:54:05 +0000591bool CodeGenFunction::EmitOMPLastprivateClauseInit(
592 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000593 if (!HaveInsertPoint())
594 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000595 bool HasAtLeastOneLastprivate = false;
596 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000597 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000598 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000599 auto IRef = C->varlist_begin();
600 auto IDestRef = C->destination_exprs().begin();
601 for (auto *IInit : C->private_copies()) {
602 // Keep the address of the original variable for future update at the end
603 // of the loop.
604 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
605 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
606 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000607 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000608 DeclRefExpr DRE(
609 const_cast<VarDecl *>(OrigVD),
610 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
611 OrigVD) != nullptr,
612 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
613 return EmitLValue(&DRE).getAddress();
614 });
615 // Check if the variable is also a firstprivate: in this case IInit is
616 // not generated. Initialization of this variable will happen in codegen
617 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000618 if (IInit) {
619 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
620 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000621 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000622 // Emit private VarDecl with copy init.
623 EmitDecl(*VD);
624 return GetAddrOfLocalVar(VD);
625 });
626 assert(IsRegistered &&
627 "lastprivate var already registered as private");
628 (void)IsRegistered;
629 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000630 }
631 ++IRef, ++IDestRef;
632 }
633 }
634 return HasAtLeastOneLastprivate;
635}
636
637void CodeGenFunction::EmitOMPLastprivateClauseFinal(
638 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000639 if (!HaveInsertPoint())
640 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000641 // Emit following code:
642 // if (<IsLastIterCond>) {
643 // orig_var1 = private_orig_var1;
644 // ...
645 // orig_varn = private_orig_varn;
646 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000647 llvm::BasicBlock *ThenBB = nullptr;
648 llvm::BasicBlock *DoneBB = nullptr;
649 if (IsLastIterCond) {
650 ThenBB = createBasicBlock(".omp.lastprivate.then");
651 DoneBB = createBasicBlock(".omp.lastprivate.done");
652 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
653 EmitBlock(ThenBB);
654 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000655 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000656 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000657 auto IC = LoopDirective->counters().begin();
658 for (auto F : LoopDirective->finals()) {
659 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
660 LoopCountersAndUpdates[D] = F;
661 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000662 }
663 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000664 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
665 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
666 auto IRef = C->varlist_begin();
667 auto ISrcRef = C->source_exprs().begin();
668 auto IDestRef = C->destination_exprs().begin();
669 for (auto *AssignOp : C->assignment_ops()) {
670 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
671 QualType Type = PrivateVD->getType();
672 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
673 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
674 // If lastprivate variable is a loop control variable for loop-based
675 // directive, update its value before copyin back to original
676 // variable.
677 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
678 EmitIgnoredExpr(UpExpr);
679 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
680 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
681 // Get the address of the original variable.
682 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
683 // Get the address of the private variable.
684 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
685 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
686 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000687 Address(Builder.CreateLoad(PrivateAddr),
688 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000689 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000690 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000691 ++IRef;
692 ++ISrcRef;
693 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000694 }
695 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000696 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000697 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000698}
699
Alexey Bataev31300ed2016-02-04 11:27:03 +0000700static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
701 LValue BaseLV, llvm::Value *Addr) {
702 Address Tmp = Address::invalid();
703 Address TopTmp = Address::invalid();
704 Address MostTopTmp = Address::invalid();
705 BaseTy = BaseTy.getNonReferenceType();
706 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
707 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
708 Tmp = CGF.CreateMemTemp(BaseTy);
709 if (TopTmp.isValid())
710 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
711 else
712 MostTopTmp = Tmp;
713 TopTmp = Tmp;
714 BaseTy = BaseTy->getPointeeType();
715 }
716 llvm::Type *Ty = BaseLV.getPointer()->getType();
717 if (Tmp.isValid())
718 Ty = Tmp.getElementType();
719 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
720 if (Tmp.isValid()) {
721 CGF.Builder.CreateStore(Addr, Tmp);
722 return MostTopTmp;
723 }
724 return Address(Addr, BaseLV.getAlignment());
725}
726
727static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
728 LValue BaseLV) {
729 BaseTy = BaseTy.getNonReferenceType();
730 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
731 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
732 if (auto *PtrTy = BaseTy->getAs<PointerType>())
733 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
734 else {
735 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
736 BaseTy->castAs<ReferenceType>());
737 }
738 BaseTy = BaseTy->getPointeeType();
739 }
740 return CGF.MakeAddrLValue(
741 Address(
742 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
743 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
744 BaseLV.getAlignment()),
745 BaseLV.getType(), BaseLV.getAlignmentSource());
746}
747
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000748void CodeGenFunction::EmitOMPReductionClauseInit(
749 const OMPExecutableDirective &D,
750 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000751 if (!HaveInsertPoint())
752 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000753 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000754 auto ILHS = C->lhs_exprs().begin();
755 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000756 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000757 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000758 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000759 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
760 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
761 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
762 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
763 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
764 Base = TempOASE->getBase()->IgnoreParenImpCasts();
765 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
766 Base = TempASE->getBase()->IgnoreParenImpCasts();
767 auto *DE = cast<DeclRefExpr>(Base);
768 auto *OrigVD = cast<VarDecl>(DE->getDecl());
769 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
770 auto OASELValueUB =
771 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
772 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000773 LValue BaseLValue =
774 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
775 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000776 // Store the address of the original variable associated with the LHS
777 // implicit variable.
778 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
779 return OASELValueLB.getAddress();
780 });
781 // Emit reduction copy.
782 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000783 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
784 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000785 // Emit VarDecl with copy init for arrays.
786 // Get the address of the original variable captured in current
787 // captured region.
788 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
789 OASELValueLB.getPointer());
790 Size = Builder.CreateNUWAdd(
791 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
792 CodeGenFunction::OpaqueValueMapping OpaqueMap(
793 *this, cast<OpaqueValueExpr>(
794 getContext()
795 .getAsVariableArrayType(PrivateVD->getType())
796 ->getSizeExpr()),
797 RValue::get(Size));
798 EmitVariablyModifiedType(PrivateVD->getType());
799 auto Emission = EmitAutoVarAlloca(*PrivateVD);
800 auto Addr = Emission.getAllocatedAddress();
801 auto *Init = PrivateVD->getInit();
802 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
803 EmitAutoVarCleanups(Emission);
804 // Emit private VarDecl with reduction init.
805 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
806 OASELValueLB.getPointer());
807 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000808 return castToBase(*this, OrigVD->getType(),
809 OASELValueLB.getType(), OriginalBaseLValue,
810 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000811 });
812 assert(IsRegistered && "private var already registered as private");
813 // Silence the warning about unused variable.
814 (void)IsRegistered;
815 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
816 return GetAddrOfLocalVar(PrivateVD);
817 });
818 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
819 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
820 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
821 Base = TempASE->getBase()->IgnoreParenImpCasts();
822 auto *DE = cast<DeclRefExpr>(Base);
823 auto *OrigVD = cast<VarDecl>(DE->getDecl());
824 auto ASELValue = EmitLValue(ASE);
825 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000826 LValue BaseLValue = loadToBegin(
827 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000828 // Store the address of the original variable associated with the LHS
829 // implicit variable.
830 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
831 return ASELValue.getAddress();
832 });
833 // Emit reduction copy.
834 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000835 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000836 OriginalBaseLValue]() -> Address {
837 // Emit private VarDecl with reduction init.
838 EmitDecl(*PrivateVD);
839 auto Addr = GetAddrOfLocalVar(PrivateVD);
840 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
841 ASELValue.getPointer());
842 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000843 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
844 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000845 });
846 assert(IsRegistered && "private var already registered as private");
847 // Silence the warning about unused variable.
848 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000849 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
850 return Builder.CreateElementBitCast(
851 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
852 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000853 });
854 } else {
855 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000856 QualType Type = PrivateVD->getType();
857 if (getContext().getAsArrayType(Type)) {
858 // Store the address of the original variable associated with the LHS
859 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000860 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
861 CapturedStmtInfo->lookup(OrigVD) != nullptr,
862 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000863 Address OriginalAddr = EmitLValue(&DRE).getAddress();
864 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
865 LHSVD]() -> Address {
866 return Builder.CreateElementBitCast(
867 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
868 "lhs.begin");
869 });
870 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
871 if (Type->isVariablyModifiedType()) {
872 CodeGenFunction::OpaqueValueMapping OpaqueMap(
873 *this, cast<OpaqueValueExpr>(
874 getContext()
875 .getAsVariableArrayType(PrivateVD->getType())
876 ->getSizeExpr()),
877 RValue::get(
878 getTypeSize(OrigVD->getType().getNonReferenceType())));
879 EmitVariablyModifiedType(Type);
880 }
881 auto Emission = EmitAutoVarAlloca(*PrivateVD);
882 auto Addr = Emission.getAllocatedAddress();
883 auto *Init = PrivateVD->getInit();
884 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
885 EmitAutoVarCleanups(Emission);
886 return Emission.getAllocatedAddress();
887 });
888 assert(IsRegistered && "private var already registered as private");
889 // Silence the warning about unused variable.
890 (void)IsRegistered;
891 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
892 return Builder.CreateElementBitCast(
893 GetAddrOfLocalVar(PrivateVD),
894 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
895 });
896 } else {
897 // Store the address of the original variable associated with the LHS
898 // implicit variable.
899 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
900 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
901 CapturedStmtInfo->lookup(OrigVD) != nullptr,
902 IRef->getType(), VK_LValue, IRef->getExprLoc());
903 return EmitLValue(&DRE).getAddress();
904 });
905 // Emit reduction copy.
906 bool IsRegistered =
907 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
908 // Emit private VarDecl with reduction init.
909 EmitDecl(*PrivateVD);
910 return GetAddrOfLocalVar(PrivateVD);
911 });
912 assert(IsRegistered && "private var already registered as private");
913 // Silence the warning about unused variable.
914 (void)IsRegistered;
915 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
916 return GetAddrOfLocalVar(PrivateVD);
917 });
918 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000919 }
920 ++ILHS, ++IRHS, ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000921 }
922 }
923}
924
925void CodeGenFunction::EmitOMPReductionClauseFinal(
926 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000927 if (!HaveInsertPoint())
928 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000929 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000930 llvm::SmallVector<const Expr *, 8> LHSExprs;
931 llvm::SmallVector<const Expr *, 8> RHSExprs;
932 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000933 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000934 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000935 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000936 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000937 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
938 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
939 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
940 }
941 if (HasAtLeastOneReduction) {
942 // Emit nowait reduction if nowait clause is present or directive is a
943 // parallel directive (it always has implicit barrier).
944 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000945 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000946 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000947 isOpenMPParallelDirective(D.getDirectiveKind()) ||
948 D.getDirectiveKind() == OMPD_simd,
949 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000950 }
951}
952
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000953static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
954 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000955 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000956 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000957 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000958 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
959 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000960 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000961 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000962 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000963 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000964 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
965 /*IgnoreResultAssign*/ true);
966 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
967 CGF, NumThreads, NumThreadsClause->getLocStart());
968 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000969 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000970 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000971 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
972 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
973 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000974 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000975 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
976 if (C->getNameModifier() == OMPD_unknown ||
977 C->getNameModifier() == OMPD_parallel) {
978 IfCond = C->getCondition();
979 break;
980 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000981 }
982 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000983 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000984}
985
986void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +0000987 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000988 // Emit parallel region as a standalone region.
989 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
990 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000991 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000992 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
993 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000994 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000995 // propagation master's thread values of threadprivate variables to local
996 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000997 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
998 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
999 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001000 }
1001 CGF.EmitOMPPrivateClause(S, PrivateScope);
1002 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1003 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001004 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001005 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001006 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001007 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +00001008}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001009
Alexey Bataev0f34da12015-07-02 04:17:07 +00001010void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1011 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001012 RunCleanupsScope BodyScope(*this);
1013 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001014 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001015 EmitIgnoredExpr(I);
1016 }
Alexander Musman3276a272015-03-21 10:12:56 +00001017 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001018 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001019 for (auto U : C->updates()) {
1020 EmitIgnoredExpr(U);
1021 }
1022 }
1023
Alexander Musmana5f070a2014-10-01 06:03:56 +00001024 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001025 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001026 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001027 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001028 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001029 // The end (updates/cleanups).
1030 EmitBlock(Continue.getBlock());
1031 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001032}
1033
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001034void CodeGenFunction::EmitOMPInnerLoop(
1035 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1036 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001037 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1038 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001039 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001040
1041 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001042 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001043 EmitBlock(CondBlock);
1044 LoopStack.push(CondBlock);
1045
1046 // If there are any cleanups between here and the loop-exit scope,
1047 // create a block to stage a loop exit along.
1048 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001049 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001050 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001051
Alexander Musmand196ef22014-10-07 08:57:09 +00001052 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001053
Alexey Bataev2df54a02015-03-12 08:53:29 +00001054 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001055 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001056 if (ExitBlock != LoopExit.getBlock()) {
1057 EmitBlock(ExitBlock);
1058 EmitBranchThroughCleanup(LoopExit);
1059 }
1060
1061 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001062 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001063
1064 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001065 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001066 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001068 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001069
1070 // Emit "IV = IV + 1" and a back-edge to the condition block.
1071 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001072 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001073 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001074 BreakContinueStack.pop_back();
1075 EmitBranch(CondBlock);
1076 LoopStack.pop();
1077 // Emit the fall-through block.
1078 EmitBlock(LoopExit.getBlock());
1079}
1080
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001081void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001082 if (!HaveInsertPoint())
1083 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001084 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001085 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001086 for (auto Init : C->inits()) {
1087 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001088 auto *OrigVD = cast<VarDecl>(
1089 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1090 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1091 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1092 VD->getInit()->getType(), VK_LValue,
1093 VD->getInit()->getExprLoc());
1094 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1095 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001096 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001097 /*capturedByInit=*/false);
1098 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001099 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001100 // Emit the linear steps for the linear clauses.
1101 // If a step is not constant, it is pre-calculated before the loop.
1102 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1103 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001104 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001105 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001106 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001107 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001108 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001109}
1110
1111static void emitLinearClauseFinal(CodeGenFunction &CGF,
1112 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001113 if (!CGF.HaveInsertPoint())
1114 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001115 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001116 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001117 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001118 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001119 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1120 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001121 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001122 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001123 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001124 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001125 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001126 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001127 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001128 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001129 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001130 }
1131 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001132}
1133
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001134static void emitAlignedClause(CodeGenFunction &CGF,
1135 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001136 if (!CGF.HaveInsertPoint())
1137 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001138 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001139 unsigned ClauseAlignment = 0;
1140 if (auto AlignmentExpr = Clause->getAlignment()) {
1141 auto AlignmentCI =
1142 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1143 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001144 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001145 for (auto E : Clause->varlists()) {
1146 unsigned Alignment = ClauseAlignment;
1147 if (Alignment == 0) {
1148 // OpenMP [2.8.1, Description]
1149 // If no optional parameter is specified, implementation-defined default
1150 // alignments for SIMD instructions on the target platforms are assumed.
1151 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001152 CGF.getContext()
1153 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1154 E->getType()->getPointeeType()))
1155 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001156 }
1157 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1158 "alignment is not power of 2");
1159 if (Alignment != 0) {
1160 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1161 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1162 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001163 }
1164 }
1165}
1166
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001167static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001168 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001169 ArrayRef<Expr *> Counters,
1170 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001171 if (!CGF.HaveInsertPoint())
1172 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001173 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001174 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001175 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1176 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001177 Address Addr = Address::invalid();
1178 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001179 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001180 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001181 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001182 Addr = VarEmission.getAllocatedAddress();
1183 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001184 });
John McCall7f416cc2015-09-08 08:05:57 +00001185 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001186 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001187 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001188}
1189
Alexey Bataev62dbb972015-04-22 11:59:37 +00001190static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1191 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1192 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001193 if (!CGF.HaveInsertPoint())
1194 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001195 {
1196 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001197 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1198 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001199 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001200 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001201 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001202 CGF.EmitIgnoredExpr(I);
1203 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001204 }
1205 // Check that loop is executed at least one time.
1206 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1207}
1208
Alexander Musman3276a272015-03-21 10:12:56 +00001209static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001210emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001211 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001212 if (!CGF.HaveInsertPoint())
1213 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001214 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001215 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001216 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001217 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1218 auto *PrivateVD =
1219 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001220 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001221 // Emit private VarDecl with copy init.
1222 CGF.EmitVarDecl(*PrivateVD);
1223 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001224 });
1225 assert(IsRegistered && "linear var already registered as private");
1226 // Silence the warning about unused variable.
1227 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001228 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001229 }
1230 }
1231}
1232
Alexey Bataev45bfad52015-08-21 12:19:04 +00001233static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001234 const OMPExecutableDirective &D,
1235 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001236 if (!CGF.HaveInsertPoint())
1237 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001238 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001239 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1240 /*ignoreResult=*/true);
1241 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1242 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1243 // In presence of finite 'safelen', it may be unsafe to mark all
1244 // the memory instructions parallel, because loop-carried
1245 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001246 if (!IsMonotonic)
1247 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001248 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001249 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1250 /*ignoreResult=*/true);
1251 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001252 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001253 // In presence of finite 'safelen', it may be unsafe to mark all
1254 // the memory instructions parallel, because loop-carried
1255 // dependences of 'safelen' iterations are possible.
1256 CGF.LoopStack.setParallel(false);
1257 }
1258}
1259
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001260void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1261 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001262 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001263 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001264 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001265 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001266}
1267
1268void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001269 if (!HaveInsertPoint())
1270 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001271 auto IC = D.counters().begin();
1272 for (auto F : D.finals()) {
1273 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001274 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001275 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1276 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1277 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001278 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001279 OMPPrivateScope VarScope(*this);
1280 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001281 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001282 (void)VarScope.Privatize();
1283 EmitIgnoredExpr(F);
1284 }
1285 ++IC;
1286 }
1287 emitLinearClauseFinal(*this, D);
1288}
1289
Alexander Musman515ad8c2014-05-22 08:54:05 +00001290void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001291 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001292 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001293 // for (IV in 0..LastIteration) BODY;
1294 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001295 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001296 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001297
Alexey Bataev62dbb972015-04-22 11:59:37 +00001298 // Emit: if (PreCond) - begin.
1299 // If the condition constant folds and can be elided, avoid emitting the
1300 // whole loop.
1301 bool CondConstant;
1302 llvm::BasicBlock *ContBlock = nullptr;
1303 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1304 if (!CondConstant)
1305 return;
1306 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001307 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1308 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001309 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1310 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001311 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001312 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001313 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001314
1315 // Emit the loop iteration variable.
1316 const Expr *IVExpr = S.getIterationVariable();
1317 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1318 CGF.EmitVarDecl(*IVDecl);
1319 CGF.EmitIgnoredExpr(S.getInit());
1320
1321 // Emit the iterations count variable.
1322 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001323 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001324 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1325 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1326 // Emit calculation of the iterations count.
1327 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001328 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001329
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001330 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001331
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001332 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001333 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001334 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001335 {
1336 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001337 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1338 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001339 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001340 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001341 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001342 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001343 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001344 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1345 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001346 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001347 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001348 CGF.EmitStopPoint(&S);
1349 },
1350 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001351 // Emit final copy of the lastprivate variables at the end of loops.
1352 if (HasLastprivateClause) {
1353 CGF.EmitOMPLastprivateClauseFinal(S);
1354 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001355 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001356 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001357 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001358 // Emit: if (PreCond) - end.
1359 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001360 CGF.EmitBranch(ContBlock);
1361 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001362 }
1363 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001364 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001365}
1366
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001367void CodeGenFunction::EmitOMPForOuterLoop(
1368 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1369 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1370 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001371 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001372
1373 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001374 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001375
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001376 assert((Ordered ||
1377 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001378 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001379
1380 // Emit outer loop.
1381 //
1382 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001383 // When schedule(dynamic,chunk_size) is specified, the iterations are
1384 // distributed to threads in the team in chunks as the threads request them.
1385 // Each thread executes a chunk of iterations, then requests another chunk,
1386 // until no chunks remain to be distributed. Each chunk contains chunk_size
1387 // iterations, except for the last chunk to be distributed, which may have
1388 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1389 //
1390 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1391 // to threads in the team in chunks as the executing threads request them.
1392 // Each thread executes a chunk of iterations, then requests another chunk,
1393 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1394 // each chunk is proportional to the number of unassigned iterations divided
1395 // by the number of threads in the team, decreasing to 1. For a chunk_size
1396 // with value k (greater than 1), the size of each chunk is determined in the
1397 // same way, with the restriction that the chunks do not contain fewer than k
1398 // iterations (except for the last chunk to be assigned, which may have fewer
1399 // than k iterations).
1400 //
1401 // When schedule(auto) is specified, the decision regarding scheduling is
1402 // delegated to the compiler and/or runtime system. The programmer gives the
1403 // implementation the freedom to choose any possible mapping of iterations to
1404 // threads in the team.
1405 //
1406 // When schedule(runtime) is specified, the decision regarding scheduling is
1407 // deferred until run time, and the schedule and chunk size are taken from the
1408 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1409 // implementation defined
1410 //
1411 // while(__kmpc_dispatch_next(&LB, &UB)) {
1412 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001413 // while (idx <= UB) { BODY; ++idx;
1414 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1415 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001416 // }
1417 //
1418 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001419 // When schedule(static, chunk_size) is specified, iterations are divided into
1420 // chunks of size chunk_size, and the chunks are assigned to the threads in
1421 // the team in a round-robin fashion in the order of the thread number.
1422 //
1423 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1424 // while (idx <= UB) { BODY; ++idx; } // inner loop
1425 // LB = LB + ST;
1426 // UB = UB + ST;
1427 // }
1428 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001429
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001430 const Expr *IVExpr = S.getIterationVariable();
1431 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1432 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1433
John McCall7f416cc2015-09-08 08:05:57 +00001434 if (DynamicOrOrdered) {
1435 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1436 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1437 IVSize, IVSigned, Ordered, UBVal, Chunk);
1438 } else {
1439 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1440 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1441 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001442
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001443 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1444
1445 // Start the loop with a block that tests the condition.
1446 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1447 EmitBlock(CondBlock);
1448 LoopStack.push(CondBlock);
1449
1450 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001451 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001452 // UB = min(UB, GlobalUB)
1453 EmitIgnoredExpr(S.getEnsureUpperBound());
1454 // IV = LB
1455 EmitIgnoredExpr(S.getInit());
1456 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001457 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001458 } else {
1459 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1460 IL, LB, UB, ST);
1461 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001462
1463 // If there are any cleanups between here and the loop-exit scope,
1464 // create a block to stage a loop exit along.
1465 auto ExitBlock = LoopExit.getBlock();
1466 if (LoopScope.requiresCleanups())
1467 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1468
1469 auto LoopBody = createBasicBlock("omp.dispatch.body");
1470 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1471 if (ExitBlock != LoopExit.getBlock()) {
1472 EmitBlock(ExitBlock);
1473 EmitBranchThroughCleanup(LoopExit);
1474 }
1475 EmitBlock(LoopBody);
1476
Alexander Musman92bdaab2015-03-12 13:37:50 +00001477 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1478 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001479 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001480 EmitIgnoredExpr(S.getInit());
1481
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001482 // Create a block for the increment.
1483 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1484 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1485
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001486 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1487 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001488 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1489 LoopStack.setParallel(!IsMonotonic);
1490 else
1491 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001492
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001493 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001494 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1495 [&S, LoopExit](CodeGenFunction &CGF) {
1496 CGF.EmitOMPLoopBody(S, LoopExit);
1497 CGF.EmitStopPoint(&S);
1498 },
1499 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1500 if (Ordered) {
1501 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1502 CGF, Loc, IVSize, IVSigned);
1503 }
1504 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001505
1506 EmitBlock(Continue.getBlock());
1507 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001508 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001509 // Emit "LB = LB + Stride", "UB = UB + Stride".
1510 EmitIgnoredExpr(S.getNextLowerBound());
1511 EmitIgnoredExpr(S.getNextUpperBound());
1512 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001513
1514 EmitBranch(CondBlock);
1515 LoopStack.pop();
1516 // Emit the fall-through block.
1517 EmitBlock(LoopExit.getBlock());
1518
1519 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001520 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001521 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001522}
1523
Alexander Musmanc6388682014-12-15 07:07:06 +00001524/// \brief Emit a helper variable and return corresponding lvalue.
1525static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1526 const DeclRefExpr *Helper) {
1527 auto VDecl = cast<VarDecl>(Helper->getDecl());
1528 CGF.EmitVarDecl(*VDecl);
1529 return CGF.EmitLValue(Helper);
1530}
1531
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001532namespace {
1533 struct ScheduleKindModifiersTy {
1534 OpenMPScheduleClauseKind Kind;
1535 OpenMPScheduleClauseModifier M1;
1536 OpenMPScheduleClauseModifier M2;
1537 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1538 OpenMPScheduleClauseModifier M1,
1539 OpenMPScheduleClauseModifier M2)
1540 : Kind(Kind), M1(M1), M2(M2) {}
1541 };
1542} // namespace
1543
Alexey Bataev38e89532015-04-16 04:54:05 +00001544bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001545 // Emit the loop iteration variable.
1546 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1547 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1548 EmitVarDecl(*IVDecl);
1549
1550 // Emit the iterations count variable.
1551 // If it is not a variable, Sema decided to calculate iterations count on each
1552 // iteration (e.g., it is foldable into a constant).
1553 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1554 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1555 // Emit calculation of the iterations count.
1556 EmitIgnoredExpr(S.getCalcLastIteration());
1557 }
1558
1559 auto &RT = CGM.getOpenMPRuntime();
1560
Alexey Bataev38e89532015-04-16 04:54:05 +00001561 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001562 // Check pre-condition.
1563 {
1564 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001565 // If the condition constant folds and can be elided, avoid emitting the
1566 // whole loop.
1567 bool CondConstant;
1568 llvm::BasicBlock *ContBlock = nullptr;
1569 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1570 if (!CondConstant)
1571 return false;
1572 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001573 auto *ThenBlock = createBasicBlock("omp.precond.then");
1574 ContBlock = createBasicBlock("omp.precond.end");
1575 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001576 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001577 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001578 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001579 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001580
1581 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001582 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001583 // Emit 'then' code.
1584 {
1585 // Emit helper vars inits.
1586 LValue LB =
1587 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1588 LValue UB =
1589 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1590 LValue ST =
1591 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1592 LValue IL =
1593 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1594
1595 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001596 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1597 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001598 // initialization of firstprivate variables and post-update of
1599 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001600 CGM.getOpenMPRuntime().emitBarrierCall(
1601 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1602 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001603 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001604 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001605 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001606 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001607 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1608 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001609 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001610 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001611
1612 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001613 llvm::Value *Chunk = nullptr;
1614 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1615 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1616 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1617 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1618 ScheduleKind = C->getScheduleKind();
1619 M1 = C->getFirstScheduleModifier();
1620 M2 = C->getSecondScheduleModifier();
1621 if (const auto *Ch = C->getChunkSize()) {
1622 Chunk = EmitScalarExpr(Ch);
1623 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1624 S.getIterationVariable()->getType(),
1625 S.getLocStart());
1626 }
1627 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001628 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1629 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001630 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001631 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1632 // If the static schedule kind is specified or if the ordered clause is
1633 // specified, and if no monotonic modifier is specified, the effect will
1634 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001635 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001636 /* Chunked */ Chunk != nullptr) &&
1637 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001638 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1639 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001640 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1641 // When no chunk_size is specified, the iteration space is divided into
1642 // chunks that are approximately equal in size, and at most one chunk is
1643 // distributed to each thread. Note that the size of the chunks is
1644 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001645 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1646 IVSize, IVSigned, Ordered,
1647 IL.getAddress(), LB.getAddress(),
1648 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001649 auto LoopExit =
1650 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001651 // UB = min(UB, GlobalUB);
1652 EmitIgnoredExpr(S.getEnsureUpperBound());
1653 // IV = LB;
1654 EmitIgnoredExpr(S.getInit());
1655 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001656 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1657 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001658 [&S, LoopExit](CodeGenFunction &CGF) {
1659 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001660 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001661 },
1662 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001663 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001664 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001665 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001666 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001667 const bool IsMonotonic = Ordered ||
1668 ScheduleKind == OMPC_SCHEDULE_static ||
1669 ScheduleKind == OMPC_SCHEDULE_unknown ||
1670 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1671 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001672 // Emit the outer loop, which requests its work chunk [LB..UB] from
1673 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001674 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001675 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1676 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001677 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001678 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001679 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1680 if (HasLastprivateClause)
1681 EmitOMPLastprivateClauseFinal(
1682 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001683 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001684 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1685 EmitOMPSimdFinal(S);
1686 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001687 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001688 if (ContBlock) {
1689 EmitBranch(ContBlock);
1690 EmitBlock(ContBlock, true);
1691 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001692 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001693 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001694}
1695
1696void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001697 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001698 {
1699 OMPLexicalScope Scope(*this, S);
1700 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1701 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1702 };
1703 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1704 S.hasCancel());
1705 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001706
1707 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001708 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001709 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1710 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001711}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001712
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001713void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001714 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001715 {
1716 OMPLexicalScope Scope(*this, S);
1717 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1718 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1719 };
1720 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1721 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001722
1723 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001724 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001725 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1726 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001727}
1728
Alexey Bataev2df54a02015-03-12 08:53:29 +00001729static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1730 const Twine &Name,
1731 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001732 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001733 if (Init)
1734 CGF.EmitScalarInit(Init, LVal);
1735 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001736}
1737
Alexey Bataev3392d762016-02-16 11:18:12 +00001738void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001739 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1740 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001741 bool HasLastprivates = false;
1742 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1743 auto &C = CGF.CGM.getContext();
1744 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1745 // Emit helper vars inits.
1746 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1747 CGF.Builder.getInt32(0));
1748 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1749 : CGF.Builder.getInt32(0);
1750 LValue UB =
1751 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1752 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1753 CGF.Builder.getInt32(1));
1754 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1755 CGF.Builder.getInt32(0));
1756 // Loop counter.
1757 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1758 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1759 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1760 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1761 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1762 // Generate condition for loop.
1763 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1764 OK_Ordinary, S.getLocStart(),
1765 /*fpContractable=*/false);
1766 // Increment for loop counter.
1767 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1768 S.getLocStart());
1769 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1770 // Iterate through all sections and emit a switch construct:
1771 // switch (IV) {
1772 // case 0:
1773 // <SectionStmt[0]>;
1774 // break;
1775 // ...
1776 // case <NumSection> - 1:
1777 // <SectionStmt[<NumSection> - 1]>;
1778 // break;
1779 // }
1780 // .omp.sections.exit:
1781 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1782 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1783 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1784 CS == nullptr ? 1 : CS->size());
1785 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001786 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001787 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001788 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1789 CGF.EmitBlock(CaseBB);
1790 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001791 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001792 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001793 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001794 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001795 } else {
1796 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1797 CGF.EmitBlock(CaseBB);
1798 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1799 CGF.EmitStmt(Stmt);
1800 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001801 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001802 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001803 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001804
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001805 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1806 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001807 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001808 // initialization of firstprivate variables and post-update of lastprivate
1809 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001810 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1811 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1812 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001813 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001814 CGF.EmitOMPPrivateClause(S, LoopScope);
1815 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1816 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1817 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001818
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001819 // Emit static non-chunked loop.
1820 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1821 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1822 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1823 UB.getAddress(), ST.getAddress());
1824 // UB = min(UB, GlobalUB);
1825 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1826 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1827 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1828 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1829 // IV = LB;
1830 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1831 // while (idx <= UB) { BODY; ++idx; }
1832 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1833 [](CodeGenFunction &) {});
1834 // Tell the runtime we are done.
1835 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1836 CGF.EmitOMPReductionClauseFinal(S);
1837
1838 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1839 if (HasLastprivates)
1840 CGF.EmitOMPLastprivateClauseFinal(
1841 S, CGF.Builder.CreateIsNotNull(
1842 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001843 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001844
1845 bool HasCancel = false;
1846 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1847 HasCancel = OSD->hasCancel();
1848 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1849 HasCancel = OPSD->hasCancel();
1850 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1851 HasCancel);
1852 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1853 // clause. Otherwise the barrier will be generated by the codegen for the
1854 // directive.
1855 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001856 // Emit implicit barrier to synchronize threads and avoid data races on
1857 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001858 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1859 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001860 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001861}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001862
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001863void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001864 {
1865 OMPLexicalScope Scope(*this, S);
1866 EmitSections(S);
1867 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001868 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001869 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001870 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1871 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001872 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001873}
1874
1875void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001876 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001877 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1878 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001879 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001880 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1881 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001882}
1883
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001884void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001885 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001886 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001887 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001888 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001889 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001890 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001891 // Build a list of copyprivate variables along with helper expressions
1892 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001893 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001894 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001895 DestExprs.append(C->destination_exprs().begin(),
1896 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001897 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001898 AssignmentOps.append(C->assignment_ops().begin(),
1899 C->assignment_ops().end());
1900 }
Alexey Bataev3392d762016-02-16 11:18:12 +00001901 {
1902 OMPLexicalScope Scope(*this, S);
1903 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00001904 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001905 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00001906 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00001907 CGF.EmitOMPPrivateClause(S, SingleScope);
1908 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00001909 CGF.EmitStmt(
1910 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1911 };
1912 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1913 CopyprivateVars, DestExprs,
1914 SrcExprs, AssignmentOps);
1915 }
1916 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1917 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00001918 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00001919 CGM.getOpenMPRuntime().emitBarrierCall(
1920 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001921 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001922 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001923}
1924
Alexey Bataev8d690652014-12-04 07:23:53 +00001925void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001926 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001927 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1928 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001929 };
1930 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001931}
1932
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001933void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001934 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001935 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1936 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001937 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001938 Expr *Hint = nullptr;
1939 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1940 Hint = HintClause->getHint();
1941 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1942 S.getDirectiveName().getAsString(),
1943 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001944}
1945
Alexey Bataev671605e2015-04-13 05:28:11 +00001946void CodeGenFunction::EmitOMPParallelForDirective(
1947 const OMPParallelForDirective &S) {
1948 // Emit directive as a combined directive that consists of two implicit
1949 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001950 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001951 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1952 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001953 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001954 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001955}
1956
Alexander Musmane4e893b2014-09-23 09:33:00 +00001957void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001958 const OMPParallelForSimdDirective &S) {
1959 // Emit directive as a combined directive that consists of two implicit
1960 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001961 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001962 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1963 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001964 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001965 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001966}
1967
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001968void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001969 const OMPParallelSectionsDirective &S) {
1970 // Emit directive as a combined directive that consists of two implicit
1971 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001972 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00001973 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001974 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001975}
1976
Alexey Bataev62b63b12015-03-10 07:28:44 +00001977void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1978 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00001979 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001980 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1981 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1982 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001983 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001984 // The first function argument for tasks is a thread id, the second one is a
1985 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001986 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1987 // Get list of private variables.
1988 llvm::SmallVector<const Expr *, 8> PrivateVars;
1989 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001990 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001991 auto IRef = C->varlist_begin();
1992 for (auto *IInit : C->private_copies()) {
1993 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1994 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1995 PrivateVars.push_back(*IRef);
1996 PrivateCopies.push_back(IInit);
1997 }
1998 ++IRef;
1999 }
2000 }
2001 EmittedAsPrivate.clear();
2002 // Get list of firstprivate variables.
2003 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2004 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2005 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002006 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002007 auto IRef = C->varlist_begin();
2008 auto IElemInitRef = C->inits().begin();
2009 for (auto *IInit : C->private_copies()) {
2010 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2011 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2012 FirstprivateVars.push_back(*IRef);
2013 FirstprivateCopies.push_back(IInit);
2014 FirstprivateInits.push_back(*IElemInitRef);
2015 }
2016 ++IRef, ++IElemInitRef;
2017 }
2018 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002019 // Build list of dependences.
2020 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2021 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002022 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002023 for (auto *IRef : C->varlists()) {
2024 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2025 }
2026 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002027 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2028 CodeGenFunction &CGF) {
2029 // Set proper addresses for generated private copies.
2030 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2031 OMPPrivateScope Scope(CGF);
2032 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002033 auto *CopyFn = CGF.Builder.CreateLoad(
2034 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2035 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2036 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002037 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002038 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002039 PrivatePtrs;
2040 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2041 CallArgs.push_back(PrivatesPtr);
2042 for (auto *E : PrivateVars) {
2043 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002044 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002045 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2046 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002047 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002048 }
2049 for (auto *E : FirstprivateVars) {
2050 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002051 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002052 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2053 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002054 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002055 }
2056 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2057 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002058 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2059 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002060 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2061 }
2062 }
2063 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002064 if (*PartId) {
2065 // TODO: emit code for untied tasks.
2066 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002067 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002068 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002069 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2070 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002071 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002072 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002073 // Check if the task is final
2074 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002075 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002076 // If the condition constant folds and can be elided, try to avoid emitting
2077 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002078 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002079 bool CondConstant;
2080 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2081 Final.setInt(CondConstant);
2082 else
2083 Final.setPointer(EvaluateExprAsBool(Cond));
2084 } else {
2085 // By default the task is not final.
2086 Final.setInt(/*IntVal=*/false);
2087 }
2088 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002089 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002090 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2091 if (C->getNameModifier() == OMPD_unknown ||
2092 C->getNameModifier() == OMPD_task) {
2093 IfCond = C->getCondition();
2094 break;
2095 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002096 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002097 CGM.getOpenMPRuntime().emitTaskCall(
2098 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002099 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002100 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002101}
2102
Alexey Bataev9f797f32015-02-05 05:57:51 +00002103void CodeGenFunction::EmitOMPTaskyieldDirective(
2104 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002105 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002106}
2107
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002108void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002109 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002110}
2111
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002112void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2113 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002114}
2115
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002116void CodeGenFunction::EmitOMPTaskgroupDirective(
2117 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002118 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002119 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2120 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002121 };
2122 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2123}
2124
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002125void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002126 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002127 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002128 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2129 FlushClause->varlist_end());
2130 }
2131 return llvm::None;
2132 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002133}
2134
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002135void CodeGenFunction::EmitOMPDistributeDirective(
2136 const OMPDistributeDirective &S) {
2137 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2138}
2139
Alexey Bataev5f600d62015-09-29 03:48:57 +00002140static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2141 const CapturedStmt *S) {
2142 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2143 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2144 CGF.CapturedStmtInfo = &CapStmtInfo;
2145 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2146 Fn->addFnAttr(llvm::Attribute::NoInline);
2147 return Fn;
2148}
2149
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002150void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002151 if (!S.getAssociatedStmt())
2152 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002153 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002154 auto *C = S.getSingleClause<OMPSIMDClause>();
2155 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2156 if (C) {
2157 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2158 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2159 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2160 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2161 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2162 } else {
2163 CGF.EmitStmt(
2164 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2165 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002166 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002167 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002168}
2169
Alexey Bataevb57056f2015-01-22 06:17:56 +00002170static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002171 QualType SrcType, QualType DestType,
2172 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002173 assert(CGF.hasScalarEvaluationKind(DestType) &&
2174 "DestType must have scalar evaluation kind.");
2175 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2176 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002177 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2178 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002179 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002180 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002181}
2182
2183static CodeGenFunction::ComplexPairTy
2184convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002185 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002186 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2187 "DestType must have complex evaluation kind.");
2188 CodeGenFunction::ComplexPairTy ComplexVal;
2189 if (Val.isScalar()) {
2190 // Convert the input element to the element type of the complex.
2191 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002192 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2193 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002194 ComplexVal = CodeGenFunction::ComplexPairTy(
2195 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2196 } else {
2197 assert(Val.isComplex() && "Must be a scalar or complex.");
2198 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2199 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2200 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002201 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002202 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002203 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002204 }
2205 return ComplexVal;
2206}
2207
Alexey Bataev5e018f92015-04-23 06:35:10 +00002208static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2209 LValue LVal, RValue RVal) {
2210 if (LVal.isGlobalReg()) {
2211 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2212 } else {
2213 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2214 : llvm::Monotonic,
2215 LVal.isVolatile(), /*IsInit=*/false);
2216 }
2217}
2218
Alexey Bataev8524d152016-01-21 12:35:58 +00002219void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2220 QualType RValTy, SourceLocation Loc) {
2221 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002222 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002223 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2224 *this, RVal, RValTy, LVal.getType(), Loc)),
2225 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002226 break;
2227 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002228 EmitStoreOfComplex(
2229 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002230 /*isInit=*/false);
2231 break;
2232 case TEK_Aggregate:
2233 llvm_unreachable("Must be a scalar or complex.");
2234 }
2235}
2236
Alexey Bataevb57056f2015-01-22 06:17:56 +00002237static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2238 const Expr *X, const Expr *V,
2239 SourceLocation Loc) {
2240 // v = x;
2241 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2242 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2243 LValue XLValue = CGF.EmitLValue(X);
2244 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002245 RValue Res = XLValue.isGlobalReg()
2246 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2247 : CGF.EmitAtomicLoad(XLValue, Loc,
2248 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002249 : llvm::Monotonic,
2250 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +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)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002256 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002257 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002258}
2259
Alexey Bataevb8329262015-02-27 06:33:30 +00002260static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2261 const Expr *X, const Expr *E,
2262 SourceLocation Loc) {
2263 // x = expr;
2264 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002265 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002266 // OpenMP, 2.12.6, atomic Construct
2267 // Any atomic construct with a seq_cst clause forces the atomically
2268 // performed operation to include an implicit flush operation without a
2269 // list.
2270 if (IsSeqCst)
2271 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2272}
2273
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002274static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2275 RValue Update,
2276 BinaryOperatorKind BO,
2277 llvm::AtomicOrdering AO,
2278 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002279 auto &Context = CGF.CGM.getContext();
2280 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002281 // expression is simple and atomic is allowed for the given type for the
2282 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002283 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002284 !Update.getScalarVal()->getType()->isIntegerTy() ||
2285 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2286 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002287 X.getAddress().getElementType())) ||
2288 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002289 !Context.getTargetInfo().hasBuiltinAtomic(
2290 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002291 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002292
2293 llvm::AtomicRMWInst::BinOp RMWOp;
2294 switch (BO) {
2295 case BO_Add:
2296 RMWOp = llvm::AtomicRMWInst::Add;
2297 break;
2298 case BO_Sub:
2299 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002300 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002301 RMWOp = llvm::AtomicRMWInst::Sub;
2302 break;
2303 case BO_And:
2304 RMWOp = llvm::AtomicRMWInst::And;
2305 break;
2306 case BO_Or:
2307 RMWOp = llvm::AtomicRMWInst::Or;
2308 break;
2309 case BO_Xor:
2310 RMWOp = llvm::AtomicRMWInst::Xor;
2311 break;
2312 case BO_LT:
2313 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2314 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2315 : llvm::AtomicRMWInst::Max)
2316 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2317 : llvm::AtomicRMWInst::UMax);
2318 break;
2319 case BO_GT:
2320 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2321 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2322 : llvm::AtomicRMWInst::Min)
2323 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2324 : llvm::AtomicRMWInst::UMin);
2325 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002326 case BO_Assign:
2327 RMWOp = llvm::AtomicRMWInst::Xchg;
2328 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002329 case BO_Mul:
2330 case BO_Div:
2331 case BO_Rem:
2332 case BO_Shl:
2333 case BO_Shr:
2334 case BO_LAnd:
2335 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002336 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002337 case BO_PtrMemD:
2338 case BO_PtrMemI:
2339 case BO_LE:
2340 case BO_GE:
2341 case BO_EQ:
2342 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002343 case BO_AddAssign:
2344 case BO_SubAssign:
2345 case BO_AndAssign:
2346 case BO_OrAssign:
2347 case BO_XorAssign:
2348 case BO_MulAssign:
2349 case BO_DivAssign:
2350 case BO_RemAssign:
2351 case BO_ShlAssign:
2352 case BO_ShrAssign:
2353 case BO_Comma:
2354 llvm_unreachable("Unsupported atomic update operation");
2355 }
2356 auto *UpdateVal = Update.getScalarVal();
2357 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2358 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002359 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002360 X.getType()->hasSignedIntegerRepresentation());
2361 }
John McCall7f416cc2015-09-08 08:05:57 +00002362 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002363 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002364}
2365
Alexey Bataev5e018f92015-04-23 06:35:10 +00002366std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002367 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2368 llvm::AtomicOrdering AO, SourceLocation Loc,
2369 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2370 // Update expressions are allowed to have the following forms:
2371 // x binop= expr; -> xrval + expr;
2372 // x++, ++x -> xrval + 1;
2373 // x--, --x -> xrval - 1;
2374 // x = x binop expr; -> xrval binop expr
2375 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002376 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2377 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002378 if (X.isGlobalReg()) {
2379 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2380 // 'xrval'.
2381 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2382 } else {
2383 // Perform compare-and-swap procedure.
2384 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002385 }
2386 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002387 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002388}
2389
2390static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2391 const Expr *X, const Expr *E,
2392 const Expr *UE, bool IsXLHSInRHSPart,
2393 SourceLocation Loc) {
2394 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2395 "Update expr in 'atomic update' must be a binary operator.");
2396 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2397 // Update expressions are allowed to have the following forms:
2398 // x binop= expr; -> xrval + expr;
2399 // x++, ++x -> xrval + 1;
2400 // x--, --x -> xrval - 1;
2401 // x = x binop expr; -> xrval binop expr
2402 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002403 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002404 LValue XLValue = CGF.EmitLValue(X);
2405 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002406 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002407 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2408 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2409 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2410 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2411 auto Gen =
2412 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2413 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2414 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2415 return CGF.EmitAnyExpr(UE);
2416 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002417 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2418 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2419 // OpenMP, 2.12.6, atomic Construct
2420 // Any atomic construct with a seq_cst clause forces the atomically
2421 // performed operation to include an implicit flush operation without a
2422 // list.
2423 if (IsSeqCst)
2424 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2425}
2426
2427static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002428 QualType SourceType, QualType ResType,
2429 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002430 switch (CGF.getEvaluationKind(ResType)) {
2431 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002432 return RValue::get(
2433 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002434 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002435 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002436 return RValue::getComplex(Res.first, Res.second);
2437 }
2438 case TEK_Aggregate:
2439 break;
2440 }
2441 llvm_unreachable("Must be a scalar or complex.");
2442}
2443
2444static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2445 bool IsPostfixUpdate, const Expr *V,
2446 const Expr *X, const Expr *E,
2447 const Expr *UE, bool IsXLHSInRHSPart,
2448 SourceLocation Loc) {
2449 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2450 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2451 RValue NewVVal;
2452 LValue VLValue = CGF.EmitLValue(V);
2453 LValue XLValue = CGF.EmitLValue(X);
2454 RValue ExprRValue = CGF.EmitAnyExpr(E);
2455 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2456 QualType NewVValType;
2457 if (UE) {
2458 // 'x' is updated with some additional value.
2459 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2460 "Update expr in 'atomic capture' must be a binary operator.");
2461 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2462 // Update expressions are allowed to have the following forms:
2463 // x binop= expr; -> xrval + expr;
2464 // x++, ++x -> xrval + 1;
2465 // x--, --x -> xrval - 1;
2466 // x = x binop expr; -> xrval binop expr
2467 // x = expr Op x; - > expr binop xrval;
2468 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2469 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2470 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2471 NewVValType = XRValExpr->getType();
2472 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2473 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2474 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2475 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2476 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2477 RValue Res = CGF.EmitAnyExpr(UE);
2478 NewVVal = IsPostfixUpdate ? XRValue : Res;
2479 return Res;
2480 };
2481 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2482 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2483 if (Res.first) {
2484 // 'atomicrmw' instruction was generated.
2485 if (IsPostfixUpdate) {
2486 // Use old value from 'atomicrmw'.
2487 NewVVal = Res.second;
2488 } else {
2489 // 'atomicrmw' does not provide new value, so evaluate it using old
2490 // value of 'x'.
2491 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2492 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2493 NewVVal = CGF.EmitAnyExpr(UE);
2494 }
2495 }
2496 } else {
2497 // 'x' is simply rewritten with some 'expr'.
2498 NewVValType = X->getType().getNonReferenceType();
2499 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002500 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002501 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2502 NewVVal = XRValue;
2503 return ExprRValue;
2504 };
2505 // Try to perform atomicrmw xchg, otherwise simple exchange.
2506 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2507 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2508 Loc, Gen);
2509 if (Res.first) {
2510 // 'atomicrmw' instruction was generated.
2511 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2512 }
2513 }
2514 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002515 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002516 // OpenMP, 2.12.6, atomic Construct
2517 // Any atomic construct with a seq_cst clause forces the atomically
2518 // performed operation to include an implicit flush operation without a
2519 // list.
2520 if (IsSeqCst)
2521 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2522}
2523
Alexey Bataevb57056f2015-01-22 06:17:56 +00002524static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002525 bool IsSeqCst, bool IsPostfixUpdate,
2526 const Expr *X, const Expr *V, const Expr *E,
2527 const Expr *UE, bool IsXLHSInRHSPart,
2528 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002529 switch (Kind) {
2530 case OMPC_read:
2531 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2532 break;
2533 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002534 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2535 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002536 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002537 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002538 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2539 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002540 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002541 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2542 IsXLHSInRHSPart, Loc);
2543 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002544 case OMPC_if:
2545 case OMPC_final:
2546 case OMPC_num_threads:
2547 case OMPC_private:
2548 case OMPC_firstprivate:
2549 case OMPC_lastprivate:
2550 case OMPC_reduction:
2551 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002552 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002553 case OMPC_collapse:
2554 case OMPC_default:
2555 case OMPC_seq_cst:
2556 case OMPC_shared:
2557 case OMPC_linear:
2558 case OMPC_aligned:
2559 case OMPC_copyin:
2560 case OMPC_copyprivate:
2561 case OMPC_flush:
2562 case OMPC_proc_bind:
2563 case OMPC_schedule:
2564 case OMPC_ordered:
2565 case OMPC_nowait:
2566 case OMPC_untied:
2567 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002568 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002569 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002570 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002571 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002572 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002573 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002574 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002575 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002576 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002577 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002578 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002579 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002580 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002581 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002582 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002583 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2584 }
2585}
2586
2587void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002588 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002589 OpenMPClauseKind Kind = OMPC_unknown;
2590 for (auto *C : S.clauses()) {
2591 // Find first clause (skip seq_cst clause, if it is first).
2592 if (C->getClauseKind() != OMPC_seq_cst) {
2593 Kind = C->getClauseKind();
2594 break;
2595 }
2596 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002597
2598 const auto *CS =
2599 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002600 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002601 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002602 }
2603 // Processing for statements under 'atomic capture'.
2604 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2605 for (const auto *C : Compound->body()) {
2606 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2607 enterFullExpression(EWC);
2608 }
2609 }
2610 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002611
Alexey Bataev3392d762016-02-16 11:18:12 +00002612 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002613 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2614 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002615 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2616 S.getV(), S.getExpr(), S.getUpdateExpr(),
2617 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002618 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002619 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002620}
2621
Samuel Antaobed3c462015-10-02 16:14:20 +00002622void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002623 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002624 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2625
2626 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002627 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002628
Samuel Antaoee8fb302016-01-06 13:42:12 +00002629 llvm::Function *Fn = nullptr;
2630 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002631
2632 // Check if we have any if clause associated with the directive.
2633 const Expr *IfCond = nullptr;
2634
2635 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2636 IfCond = C->getCondition();
2637 }
2638
2639 // Check if we have any device clause associated with the directive.
2640 const Expr *Device = nullptr;
2641 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2642 Device = C->getDevice();
2643 }
2644
Samuel Antaoee8fb302016-01-06 13:42:12 +00002645 // Check if we have an if clause whose conditional always evaluates to false
2646 // or if we do not have any targets specified. If so the target region is not
2647 // an offload entry point.
2648 bool IsOffloadEntry = true;
2649 if (IfCond) {
2650 bool Val;
2651 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2652 IsOffloadEntry = false;
2653 }
2654 if (CGM.getLangOpts().OMPTargetTriples.empty())
2655 IsOffloadEntry = false;
2656
2657 assert(CurFuncDecl && "No parent declaration for target region!");
2658 StringRef ParentName;
2659 // In case we have Ctors/Dtors we use the complete type variant to produce
2660 // the mangling of the device outlined kernel.
2661 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2662 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2663 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2664 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2665 else
2666 ParentName =
2667 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2668
2669 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2670 IsOffloadEntry);
2671
2672 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002673 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002674}
2675
Alexey Bataev13314bf2014-10-09 04:18:56 +00002676void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2677 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2678}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002679
2680void CodeGenFunction::EmitOMPCancellationPointDirective(
2681 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002682 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2683 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002684}
2685
Alexey Bataev80909872015-07-02 11:25:17 +00002686void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002687 const Expr *IfCond = nullptr;
2688 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2689 if (C->getNameModifier() == OMPD_unknown ||
2690 C->getNameModifier() == OMPD_cancel) {
2691 IfCond = C->getCondition();
2692 break;
2693 }
2694 }
2695 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002696 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002697}
2698
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002699CodeGenFunction::JumpDest
2700CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2701 if (Kind == OMPD_parallel || Kind == OMPD_task)
2702 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002703 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002704 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002705 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002706}
Michael Wong65f367f2015-07-21 13:44:28 +00002707
2708// Generate the instructions for '#pragma omp target data' directive.
2709void CodeGenFunction::EmitOMPTargetDataDirective(
2710 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002711 // emit the code inside the construct for now
2712 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002713 CGM.getOpenMPRuntime().emitInlinedDirective(
2714 *this, OMPD_target_data,
2715 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002716}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002717
Samuel Antaodf67fc42016-01-19 19:15:56 +00002718void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2719 const OMPTargetEnterDataDirective &S) {
2720 // TODO: codegen for target enter data.
2721}
2722
Samuel Antao72590762016-01-19 20:04:50 +00002723void CodeGenFunction::EmitOMPTargetExitDataDirective(
2724 const OMPTargetExitDataDirective &S) {
2725 // TODO: codegen for target exit data.
2726}
2727
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002728void CodeGenFunction::EmitOMPTargetParallelDirective(
2729 const OMPTargetParallelDirective &S) {
2730 // TODO: codegen for target parallel.
2731}
2732
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002733void CodeGenFunction::EmitOMPTargetParallelForDirective(
2734 const OMPTargetParallelForDirective &S) {
2735 // TODO: codegen for target parallel for.
2736}
2737
Alexey Bataev49f6e782015-12-01 04:18:41 +00002738void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2739 // emit the code inside the construct for now
2740 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2741 CGM.getOpenMPRuntime().emitInlinedDirective(
2742 *this, OMPD_taskloop,
2743 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2744}
2745
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002746void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2747 const OMPTaskLoopSimdDirective &S) {
2748 // emit the code inside the construct for now
2749 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2750 CGM.getOpenMPRuntime().emitInlinedDirective(
2751 *this, OMPD_taskloop_simd,
2752 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2753}
2754