blob: 457d21e3dc269117d4421dc64645500ccb0fcbff [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
Alexey Bataev3392d762016-02-16 11:18:12 +000040public:
41 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
42 : Scope(CGF, S.getSourceRange()) {
43 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000044 }
45};
46} // namespace
47
Alexey Bataev1189bd02016-01-26 12:20:39 +000048llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
49 auto &C = getContext();
50 llvm::Value *Size = nullptr;
51 auto SizeInChars = C.getTypeSizeInChars(Ty);
52 if (SizeInChars.isZero()) {
53 // getTypeSizeInChars() returns 0 for a VLA.
54 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
55 llvm::Value *ArraySize;
56 std::tie(ArraySize, Ty) = getVLASize(VAT);
57 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
58 }
59 SizeInChars = C.getTypeSizeInChars(Ty);
60 if (SizeInChars.isZero())
61 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
62 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
63 } else
64 Size = CGM.getSize(SizeInChars);
65 return Size;
66}
67
Alexey Bataev2377fe92015-09-10 08:12:02 +000068void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000069 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000070 const RecordDecl *RD = S.getCapturedRecordDecl();
71 auto CurField = RD->field_begin();
72 auto CurCap = S.captures().begin();
73 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
74 E = S.capture_init_end();
75 I != E; ++I, ++CurField, ++CurCap) {
76 if (CurField->hasCapturedVLAType()) {
77 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000078 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000079 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000080 } else if (CurCap->capturesThis())
81 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000082 else if (CurCap->capturesVariableByCopy())
83 CapturedVars.push_back(
84 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
85 else {
86 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000087 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000088 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000089 }
90}
91
Samuel Antao4af1b7b2015-12-02 17:44:43 +000092static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
93 StringRef Name, LValue AddrLV,
94 bool isReferenceType = false) {
95 ASTContext &Ctx = CGF.getContext();
96
97 auto *CastedPtr = CGF.EmitScalarConversion(
98 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
99 Ctx.getPointerType(DstType), SourceLocation());
100 auto TmpAddr =
101 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
102 .getAddress();
103
104 // If we are dealing with references we need to return the address of the
105 // reference instead of the reference of the value.
106 if (isReferenceType) {
107 QualType RefType = Ctx.getLValueReferenceType(DstType);
108 auto *RefVal = TmpAddr.getPointer();
109 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
110 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
111 CGF.EmitScalarInit(RefVal, TmpLVal);
112 }
113
114 return TmpAddr;
115}
116
Alexey Bataev2377fe92015-09-10 08:12:02 +0000117llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000118CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000119 assert(
120 CapturedStmtInfo &&
121 "CapturedStmtInfo should be set when generating the captured function");
122 const CapturedDecl *CD = S.getCapturedDecl();
123 const RecordDecl *RD = S.getCapturedRecordDecl();
124 assert(CD->hasBody() && "missing CapturedDecl body");
125
126 // Build the argument list.
127 ASTContext &Ctx = CGM.getContext();
128 FunctionArgList Args;
129 Args.append(CD->param_begin(),
130 std::next(CD->param_begin(), CD->getContextParamPosition()));
131 auto I = S.captures().begin();
132 for (auto *FD : RD->fields()) {
133 QualType ArgType = FD->getType();
134 IdentifierInfo *II = nullptr;
135 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000136
137 // If this is a capture by copy and the type is not a pointer, the outlined
138 // function argument type should be uintptr and the value properly casted to
139 // uintptr. This is necessary given that the runtime library is only able to
140 // deal with pointers. We can pass in the same way the VLA type sizes to the
141 // outlined function.
142 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
143 I->capturesVariableArrayType())
144 ArgType = Ctx.getUIntPtrType();
145
146 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000147 CapVar = I->getCapturedVar();
148 II = CapVar->getIdentifier();
149 } else if (I->capturesThis())
150 II = &getContext().Idents.get("this");
151 else {
152 assert(I->capturesVariableArrayType());
153 II = &getContext().Idents.get("vla");
154 }
155 if (ArgType->isVariablyModifiedType())
156 ArgType = getContext().getVariableArrayDecayedType(ArgType);
157 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
158 FD->getLocation(), II, ArgType));
159 ++I;
160 }
161 Args.append(
162 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
163 CD->param_end());
164
165 // Create the function declaration.
166 FunctionType::ExtInfo ExtInfo;
167 const CGFunctionInfo &FuncInfo =
168 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
169 /*IsVariadic=*/false);
170 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
171
172 llvm::Function *F = llvm::Function::Create(
173 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
174 CapturedStmtInfo->getHelperName(), &CGM.getModule());
175 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
176 if (CD->isNothrow())
177 F->addFnAttr(llvm::Attribute::NoUnwind);
178
179 // Generate the function.
180 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
181 CD->getBody()->getLocStart());
182 unsigned Cnt = CD->getContextParamPosition();
183 I = S.captures().begin();
184 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000185 // If we are capturing a pointer by copy we don't need to do anything, just
186 // use the value that we get from the arguments.
187 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
188 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000189 ++Cnt;
190 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000191 continue;
192 }
193
Alexey Bataev2377fe92015-09-10 08:12:02 +0000194 LValue ArgLVal =
195 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
196 AlignmentSource::Decl);
197 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000198 LValue CastedArgLVal =
199 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
200 Args[Cnt]->getName(), ArgLVal),
201 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000203 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000204 auto VAT = FD->getCapturedVLAType();
205 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
206 } else if (I->capturesVariable()) {
207 auto *Var = I->getCapturedVar();
208 QualType VarTy = Var->getType();
209 Address ArgAddr = ArgLVal.getAddress();
210 if (!VarTy->isReferenceType()) {
211 ArgAddr = EmitLoadOfReference(
212 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
213 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000214 setAddrOfLocalVar(
215 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000216 } else if (I->capturesVariableByCopy()) {
217 assert(!FD->getType()->isAnyPointerType() &&
218 "Not expecting a captured pointer.");
219 auto *Var = I->getCapturedVar();
220 QualType VarTy = Var->getType();
221 setAddrOfLocalVar(I->getCapturedVar(),
222 castValueFromUintptr(*this, FD->getType(),
223 Args[Cnt]->getName(), ArgLVal,
224 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000225 } else {
226 // If 'this' is captured, load it into CXXThisValue.
227 assert(I->capturesThis());
228 CXXThisValue =
229 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
230 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000231 ++Cnt;
232 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 }
234
Serge Pavlov3a561452015-12-06 14:32:39 +0000235 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000236 CapturedStmtInfo->EmitBody(*this, CD->getBody());
237 FinishFunction(CD->getBodyRBrace());
238
239 return F;
240}
241
Alexey Bataev9959db52014-05-06 10:08:46 +0000242//===----------------------------------------------------------------------===//
243// OpenMP Directive Emission
244//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000245void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000246 Address DestAddr, Address SrcAddr, QualType OriginalType,
247 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000248 // Perform element-by-element initialization.
249 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000250
251 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000252 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000253 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
254 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
255
256 auto SrcBegin = SrcAddr.getPointer();
257 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000258 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000259 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
260 // The basic structure here is a while-do loop.
261 auto BodyBB = createBasicBlock("omp.arraycpy.body");
262 auto DoneBB = createBasicBlock("omp.arraycpy.done");
263 auto IsEmpty =
264 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
265 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000266
Alexey Bataev420d45b2015-04-14 05:11:24 +0000267 // Enter the loop body, making that address the current address.
268 auto EntryBB = Builder.GetInsertBlock();
269 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000270
271 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
272
273 llvm::PHINode *SrcElementPHI =
274 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
275 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
276 Address SrcElementCurrent =
277 Address(SrcElementPHI,
278 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
279
280 llvm::PHINode *DestElementPHI =
281 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
282 DestElementPHI->addIncoming(DestBegin, EntryBB);
283 Address DestElementCurrent =
284 Address(DestElementPHI,
285 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000286
Alexey Bataev420d45b2015-04-14 05:11:24 +0000287 // Emit copy.
288 CopyGen(DestElementCurrent, SrcElementCurrent);
289
290 // Shift the address forward by one element.
291 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000292 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000293 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000294 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000295 // Check whether we've reached the end.
296 auto Done =
297 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
298 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000299 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
300 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000301
302 // Done.
303 EmitBlock(DoneBB, /*IsFinished=*/true);
304}
305
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000306/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000307/// \param DestAddr Address of the array.
308/// \param Type Type of array.
309/// \param Init Initial expression of array.
310static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
311 QualType Type, const Expr *Init) {
312 // Perform element-by-element initialization.
313 QualType ElementTy;
314
315 // Drill down to the base element type on both arrays.
316 auto ArrayTy = Type->getAsArrayTypeUnsafe();
317 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
318 DestAddr =
319 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
320
321 auto DestBegin = DestAddr.getPointer();
322 // Cast from pointer to array type to pointer to single element.
323 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
324 // The basic structure here is a while-do loop.
325 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
326 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
327 auto IsEmpty =
328 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
329 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
330
331 // Enter the loop body, making that address the current address.
332 auto EntryBB = CGF.Builder.GetInsertBlock();
333 CGF.EmitBlock(BodyBB);
334
335 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
336
337 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
338 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
339 DestElementPHI->addIncoming(DestBegin, EntryBB);
340 Address DestElementCurrent =
341 Address(DestElementPHI,
342 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
343
344 // Emit copy.
345 {
346 CodeGenFunction::RunCleanupsScope InitScope(CGF);
347 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
348 /*IsInitializer=*/false);
349 }
350
351 // Shift the address forward by one element.
352 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
353 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
354 // Check whether we've reached the end.
355 auto Done =
356 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
357 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
358 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
359
360 // Done.
361 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
362}
363
John McCall7f416cc2015-09-08 08:05:57 +0000364void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
365 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000366 const VarDecl *SrcVD, const Expr *Copy) {
367 if (OriginalType->isArrayType()) {
368 auto *BO = dyn_cast<BinaryOperator>(Copy);
369 if (BO && BO->getOpcode() == BO_Assign) {
370 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000371 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000372 } else {
373 // For arrays with complex element types perform element by element
374 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000375 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000376 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000377 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000378 // Working with the single array element, so have to remap
379 // destination and source variables to corresponding array
380 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000381 CodeGenFunction::OMPPrivateScope Remap(*this);
382 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000383 return DestElement;
384 });
385 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000386 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000387 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000388 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000389 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000390 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000391 } else {
392 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000393 CodeGenFunction::OMPPrivateScope Remap(*this);
394 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
395 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000396 (void)Remap.Privatize();
397 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000398 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000399 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000400}
401
Alexey Bataev69c62a92015-04-15 04:52:20 +0000402bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
403 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000404 if (!HaveInsertPoint())
405 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000406 bool FirstprivateIsLastprivate = false;
407 llvm::DenseSet<const VarDecl *> Lastprivates;
408 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
409 for (const auto *D : C->varlists())
410 Lastprivates.insert(
411 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
412 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000413 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000414 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000415 auto IRef = C->varlist_begin();
416 auto InitsRef = C->inits().begin();
417 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000418 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000419 FirstprivateIsLastprivate =
420 FirstprivateIsLastprivate ||
421 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
422 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000423 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
424 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
425 bool IsRegistered;
426 DeclRefExpr DRE(
427 const_cast<VarDecl *>(OrigVD),
428 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
429 OrigVD) != nullptr,
430 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000431 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000432 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000433 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000434 // Emit VarDecl with copy init for arrays.
435 // Get the address of the original variable captured in current
436 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000437 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000438 auto Emission = EmitAutoVarAlloca(*VD);
439 auto *Init = VD->getInit();
440 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
441 // Perform simple memcpy.
442 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000443 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000444 } else {
445 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000446 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000447 [this, VDInit, Init](Address DestElement,
448 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000449 // Clean up any temporaries needed by the initialization.
450 RunCleanupsScope InitScope(*this);
451 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000452 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000453 EmitAnyExprToMem(Init, DestElement,
454 Init->getType().getQualifiers(),
455 /*IsInitializer*/ false);
456 LocalDeclMap.erase(VDInit);
457 });
458 }
459 EmitAutoVarCleanups(Emission);
460 return Emission.getAllocatedAddress();
461 });
462 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000463 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000464 // Emit private VarDecl with copy init.
465 // Remap temp VDInit variable to the address of the original
466 // variable
467 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000468 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000469 EmitDecl(*VD);
470 LocalDeclMap.erase(VDInit);
471 return GetAddrOfLocalVar(VD);
472 });
473 }
474 assert(IsRegistered &&
475 "firstprivate var already registered as private");
476 // Silence the warning about unused variable.
477 (void)IsRegistered;
478 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000479 ++IRef;
480 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000481 }
482 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000483 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000484}
485
Alexey Bataev03b340a2014-10-21 03:16:40 +0000486void CodeGenFunction::EmitOMPPrivateClause(
487 const OMPExecutableDirective &D,
488 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000489 if (!HaveInsertPoint())
490 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000491 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000492 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000493 auto IRef = C->varlist_begin();
494 for (auto IInit : C->private_copies()) {
495 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000496 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
497 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
498 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000499 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000500 // Emit private VarDecl with copy init.
501 EmitDecl(*VD);
502 return GetAddrOfLocalVar(VD);
503 });
504 assert(IsRegistered && "private var already registered as private");
505 // Silence the warning about unused variable.
506 (void)IsRegistered;
507 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000508 ++IRef;
509 }
510 }
511}
512
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000513bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000514 if (!HaveInsertPoint())
515 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000516 // threadprivate_var1 = master_threadprivate_var1;
517 // operator=(threadprivate_var2, master_threadprivate_var2);
518 // ...
519 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000520 llvm::DenseSet<const VarDecl *> CopiedVars;
521 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000522 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000523 auto IRef = C->varlist_begin();
524 auto ISrcRef = C->source_exprs().begin();
525 auto IDestRef = C->destination_exprs().begin();
526 for (auto *AssignOp : C->assignment_ops()) {
527 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000528 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000529 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000530 // Get the address of the master variable. If we are emitting code with
531 // TLS support, the address is passed from the master as field in the
532 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000533 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000534 if (getLangOpts().OpenMPUseTLS &&
535 getContext().getTargetInfo().isTLSSupported()) {
536 assert(CapturedStmtInfo->lookup(VD) &&
537 "Copyin threadprivates should have been captured!");
538 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
539 VK_LValue, (*IRef)->getExprLoc());
540 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000541 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000542 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000543 MasterAddr =
544 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
545 : CGM.GetAddrOfGlobal(VD),
546 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000547 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000548 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000549 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000550 if (CopiedVars.size() == 1) {
551 // At first check if current thread is a master thread. If it is, no
552 // need to copy data.
553 CopyBegin = createBasicBlock("copyin.not.master");
554 CopyEnd = createBasicBlock("copyin.not.master.end");
555 Builder.CreateCondBr(
556 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000557 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
558 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000559 CopyBegin, CopyEnd);
560 EmitBlock(CopyBegin);
561 }
562 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
563 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000564 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000565 }
566 ++IRef;
567 ++ISrcRef;
568 ++IDestRef;
569 }
570 }
571 if (CopyEnd) {
572 // Exit out of copying procedure for non-master thread.
573 EmitBlock(CopyEnd, /*IsFinished=*/true);
574 return true;
575 }
576 return false;
577}
578
Alexey Bataev38e89532015-04-16 04:54:05 +0000579bool CodeGenFunction::EmitOMPLastprivateClauseInit(
580 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000581 if (!HaveInsertPoint())
582 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000583 bool HasAtLeastOneLastprivate = false;
584 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000585 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000586 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000587 auto IRef = C->varlist_begin();
588 auto IDestRef = C->destination_exprs().begin();
589 for (auto *IInit : C->private_copies()) {
590 // Keep the address of the original variable for future update at the end
591 // of the loop.
592 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
593 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
594 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000595 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000596 DeclRefExpr DRE(
597 const_cast<VarDecl *>(OrigVD),
598 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
599 OrigVD) != nullptr,
600 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
601 return EmitLValue(&DRE).getAddress();
602 });
603 // Check if the variable is also a firstprivate: in this case IInit is
604 // not generated. Initialization of this variable will happen in codegen
605 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000606 if (IInit) {
607 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
608 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000609 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000610 // Emit private VarDecl with copy init.
611 EmitDecl(*VD);
612 return GetAddrOfLocalVar(VD);
613 });
614 assert(IsRegistered &&
615 "lastprivate var already registered as private");
616 (void)IsRegistered;
617 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000618 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000619 ++IRef;
620 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000621 }
622 }
623 return HasAtLeastOneLastprivate;
624}
625
626void CodeGenFunction::EmitOMPLastprivateClauseFinal(
627 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000628 if (!HaveInsertPoint())
629 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000630 // Emit following code:
631 // if (<IsLastIterCond>) {
632 // orig_var1 = private_orig_var1;
633 // ...
634 // orig_varn = private_orig_varn;
635 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000636 llvm::BasicBlock *ThenBB = nullptr;
637 llvm::BasicBlock *DoneBB = nullptr;
638 if (IsLastIterCond) {
639 ThenBB = createBasicBlock(".omp.lastprivate.then");
640 DoneBB = createBasicBlock(".omp.lastprivate.done");
641 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
642 EmitBlock(ThenBB);
643 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000644 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000645 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000646 auto IC = LoopDirective->counters().begin();
647 for (auto F : LoopDirective->finals()) {
648 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
649 LoopCountersAndUpdates[D] = F;
650 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000651 }
652 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000653 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
654 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
655 auto IRef = C->varlist_begin();
656 auto ISrcRef = C->source_exprs().begin();
657 auto IDestRef = C->destination_exprs().begin();
658 for (auto *AssignOp : C->assignment_ops()) {
659 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
660 QualType Type = PrivateVD->getType();
661 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
662 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
663 // If lastprivate variable is a loop control variable for loop-based
664 // directive, update its value before copyin back to original
665 // variable.
666 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
667 EmitIgnoredExpr(UpExpr);
668 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
669 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
670 // Get the address of the original variable.
671 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
672 // Get the address of the private variable.
673 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
674 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
675 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000676 Address(Builder.CreateLoad(PrivateAddr),
677 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000678 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000679 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000680 ++IRef;
681 ++ISrcRef;
682 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000683 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000684 if (auto *PostUpdate = C->getPostUpdateExpr())
685 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000686 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000687 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000688 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000689}
690
Alexey Bataev31300ed2016-02-04 11:27:03 +0000691static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
692 LValue BaseLV, llvm::Value *Addr) {
693 Address Tmp = Address::invalid();
694 Address TopTmp = Address::invalid();
695 Address MostTopTmp = Address::invalid();
696 BaseTy = BaseTy.getNonReferenceType();
697 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
698 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
699 Tmp = CGF.CreateMemTemp(BaseTy);
700 if (TopTmp.isValid())
701 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
702 else
703 MostTopTmp = Tmp;
704 TopTmp = Tmp;
705 BaseTy = BaseTy->getPointeeType();
706 }
707 llvm::Type *Ty = BaseLV.getPointer()->getType();
708 if (Tmp.isValid())
709 Ty = Tmp.getElementType();
710 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
711 if (Tmp.isValid()) {
712 CGF.Builder.CreateStore(Addr, Tmp);
713 return MostTopTmp;
714 }
715 return Address(Addr, BaseLV.getAlignment());
716}
717
718static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
719 LValue BaseLV) {
720 BaseTy = BaseTy.getNonReferenceType();
721 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
722 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
723 if (auto *PtrTy = BaseTy->getAs<PointerType>())
724 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
725 else {
726 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
727 BaseTy->castAs<ReferenceType>());
728 }
729 BaseTy = BaseTy->getPointeeType();
730 }
731 return CGF.MakeAddrLValue(
732 Address(
733 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
734 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
735 BaseLV.getAlignment()),
736 BaseLV.getType(), BaseLV.getAlignmentSource());
737}
738
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000739void CodeGenFunction::EmitOMPReductionClauseInit(
740 const OMPExecutableDirective &D,
741 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000742 if (!HaveInsertPoint())
743 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000744 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000745 auto ILHS = C->lhs_exprs().begin();
746 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000747 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000748 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000749 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000750 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
751 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
752 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
753 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
754 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
755 Base = TempOASE->getBase()->IgnoreParenImpCasts();
756 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
757 Base = TempASE->getBase()->IgnoreParenImpCasts();
758 auto *DE = cast<DeclRefExpr>(Base);
759 auto *OrigVD = cast<VarDecl>(DE->getDecl());
760 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
761 auto OASELValueUB =
762 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
763 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000764 LValue BaseLValue =
765 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
766 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000767 // Store the address of the original variable associated with the LHS
768 // implicit variable.
769 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
770 return OASELValueLB.getAddress();
771 });
772 // Emit reduction copy.
773 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000774 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
775 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000776 // Emit VarDecl with copy init for arrays.
777 // Get the address of the original variable captured in current
778 // captured region.
779 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
780 OASELValueLB.getPointer());
781 Size = Builder.CreateNUWAdd(
782 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
783 CodeGenFunction::OpaqueValueMapping OpaqueMap(
784 *this, cast<OpaqueValueExpr>(
785 getContext()
786 .getAsVariableArrayType(PrivateVD->getType())
787 ->getSizeExpr()),
788 RValue::get(Size));
789 EmitVariablyModifiedType(PrivateVD->getType());
790 auto Emission = EmitAutoVarAlloca(*PrivateVD);
791 auto Addr = Emission.getAllocatedAddress();
792 auto *Init = PrivateVD->getInit();
793 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
794 EmitAutoVarCleanups(Emission);
795 // Emit private VarDecl with reduction init.
796 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
797 OASELValueLB.getPointer());
798 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000799 return castToBase(*this, OrigVD->getType(),
800 OASELValueLB.getType(), OriginalBaseLValue,
801 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000802 });
803 assert(IsRegistered && "private var already registered as private");
804 // Silence the warning about unused variable.
805 (void)IsRegistered;
806 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
807 return GetAddrOfLocalVar(PrivateVD);
808 });
809 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
810 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
811 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
812 Base = TempASE->getBase()->IgnoreParenImpCasts();
813 auto *DE = cast<DeclRefExpr>(Base);
814 auto *OrigVD = cast<VarDecl>(DE->getDecl());
815 auto ASELValue = EmitLValue(ASE);
816 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000817 LValue BaseLValue = loadToBegin(
818 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000819 // Store the address of the original variable associated with the LHS
820 // implicit variable.
821 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
822 return ASELValue.getAddress();
823 });
824 // Emit reduction copy.
825 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000826 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000827 OriginalBaseLValue]() -> Address {
828 // Emit private VarDecl with reduction init.
829 EmitDecl(*PrivateVD);
830 auto Addr = GetAddrOfLocalVar(PrivateVD);
831 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
832 ASELValue.getPointer());
833 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000834 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
835 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000836 });
837 assert(IsRegistered && "private var already registered as private");
838 // Silence the warning about unused variable.
839 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000840 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
841 return Builder.CreateElementBitCast(
842 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
843 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000844 });
845 } else {
846 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000847 QualType Type = PrivateVD->getType();
848 if (getContext().getAsArrayType(Type)) {
849 // Store the address of the original variable associated with the LHS
850 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000851 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
852 CapturedStmtInfo->lookup(OrigVD) != nullptr,
853 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000854 Address OriginalAddr = EmitLValue(&DRE).getAddress();
855 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
856 LHSVD]() -> Address {
857 return Builder.CreateElementBitCast(
858 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
859 "lhs.begin");
860 });
861 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
862 if (Type->isVariablyModifiedType()) {
863 CodeGenFunction::OpaqueValueMapping OpaqueMap(
864 *this, cast<OpaqueValueExpr>(
865 getContext()
866 .getAsVariableArrayType(PrivateVD->getType())
867 ->getSizeExpr()),
868 RValue::get(
869 getTypeSize(OrigVD->getType().getNonReferenceType())));
870 EmitVariablyModifiedType(Type);
871 }
872 auto Emission = EmitAutoVarAlloca(*PrivateVD);
873 auto Addr = Emission.getAllocatedAddress();
874 auto *Init = PrivateVD->getInit();
875 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
876 EmitAutoVarCleanups(Emission);
877 return Emission.getAllocatedAddress();
878 });
879 assert(IsRegistered && "private var already registered as private");
880 // Silence the warning about unused variable.
881 (void)IsRegistered;
882 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
883 return Builder.CreateElementBitCast(
884 GetAddrOfLocalVar(PrivateVD),
885 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
886 });
887 } else {
888 // Store the address of the original variable associated with the LHS
889 // implicit variable.
890 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
891 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
892 CapturedStmtInfo->lookup(OrigVD) != nullptr,
893 IRef->getType(), VK_LValue, IRef->getExprLoc());
894 return EmitLValue(&DRE).getAddress();
895 });
896 // Emit reduction copy.
897 bool IsRegistered =
898 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
899 // Emit private VarDecl with reduction init.
900 EmitDecl(*PrivateVD);
901 return GetAddrOfLocalVar(PrivateVD);
902 });
903 assert(IsRegistered && "private var already registered as private");
904 // Silence the warning about unused variable.
905 (void)IsRegistered;
906 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
907 return GetAddrOfLocalVar(PrivateVD);
908 });
909 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000910 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000911 ++ILHS;
912 ++IRHS;
913 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000914 }
915 }
916}
917
918void CodeGenFunction::EmitOMPReductionClauseFinal(
919 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000920 if (!HaveInsertPoint())
921 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000922 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000923 llvm::SmallVector<const Expr *, 8> LHSExprs;
924 llvm::SmallVector<const Expr *, 8> RHSExprs;
925 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000926 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000927 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000928 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000929 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000930 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
931 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
932 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
933 }
934 if (HasAtLeastOneReduction) {
935 // Emit nowait reduction if nowait clause is present or directive is a
936 // parallel directive (it always has implicit barrier).
937 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000938 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000939 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000940 isOpenMPParallelDirective(D.getDirectiveKind()) ||
941 D.getDirectiveKind() == OMPD_simd,
942 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000943 }
944}
945
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000946static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
947 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000948 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000949 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000950 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000951 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
952 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000953 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000954 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000955 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000956 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000957 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
958 /*IgnoreResultAssign*/ true);
959 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
960 CGF, NumThreads, NumThreadsClause->getLocStart());
961 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000962 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000963 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000964 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
965 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
966 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000967 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000968 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
969 if (C->getNameModifier() == OMPD_unknown ||
970 C->getNameModifier() == OMPD_parallel) {
971 IfCond = C->getCondition();
972 break;
973 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000974 }
975 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000976 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000977}
978
979void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +0000980 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000981 // Emit parallel region as a standalone region.
982 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
983 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000984 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000985 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
986 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000987 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000988 // propagation master's thread values of threadprivate variables to local
989 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000990 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
991 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
992 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000993 }
994 CGF.EmitOMPPrivateClause(S, PrivateScope);
995 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
996 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000997 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000998 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000999 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001000 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +00001001}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001002
Alexey Bataev0f34da12015-07-02 04:17:07 +00001003void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1004 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001005 RunCleanupsScope BodyScope(*this);
1006 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001007 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001008 EmitIgnoredExpr(I);
1009 }
Alexander Musman3276a272015-03-21 10:12:56 +00001010 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001011 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001012 for (auto U : C->updates()) {
1013 EmitIgnoredExpr(U);
1014 }
1015 }
1016
Alexander Musmana5f070a2014-10-01 06:03:56 +00001017 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001018 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001019 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001020 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001021 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001022 // The end (updates/cleanups).
1023 EmitBlock(Continue.getBlock());
1024 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001025}
1026
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001027void CodeGenFunction::EmitOMPInnerLoop(
1028 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1029 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001030 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1031 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001032 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001033
1034 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001035 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001036 EmitBlock(CondBlock);
1037 LoopStack.push(CondBlock);
1038
1039 // If there are any cleanups between here and the loop-exit scope,
1040 // create a block to stage a loop exit along.
1041 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001042 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001043 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001044
Alexander Musmand196ef22014-10-07 08:57:09 +00001045 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001046
Alexey Bataev2df54a02015-03-12 08:53:29 +00001047 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001048 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001049 if (ExitBlock != LoopExit.getBlock()) {
1050 EmitBlock(ExitBlock);
1051 EmitBranchThroughCleanup(LoopExit);
1052 }
1053
1054 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001055 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001056
1057 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001058 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001059 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1060
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001061 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001062
1063 // Emit "IV = IV + 1" and a back-edge to the condition block.
1064 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001065 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001066 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001067 BreakContinueStack.pop_back();
1068 EmitBranch(CondBlock);
1069 LoopStack.pop();
1070 // Emit the fall-through block.
1071 EmitBlock(LoopExit.getBlock());
1072}
1073
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001074void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001075 if (!HaveInsertPoint())
1076 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001077 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001078 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001079 for (auto Init : C->inits()) {
1080 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001081 auto *OrigVD = cast<VarDecl>(
1082 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1083 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1084 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1085 VD->getInit()->getType(), VK_LValue,
1086 VD->getInit()->getExprLoc());
1087 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1088 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001089 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001090 /*capturedByInit=*/false);
1091 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001092 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001093 // Emit the linear steps for the linear clauses.
1094 // If a step is not constant, it is pre-calculated before the loop.
1095 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1096 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001097 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001098 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001099 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001100 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001101 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001102}
1103
1104static void emitLinearClauseFinal(CodeGenFunction &CGF,
1105 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001106 if (!CGF.HaveInsertPoint())
1107 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001108 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001109 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001110 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001111 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001112 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1113 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001114 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001115 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001116 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001117 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001118 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001119 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001120 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001121 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001122 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001123 }
1124 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001125}
1126
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001127static void emitAlignedClause(CodeGenFunction &CGF,
1128 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001129 if (!CGF.HaveInsertPoint())
1130 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001131 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001132 unsigned ClauseAlignment = 0;
1133 if (auto AlignmentExpr = Clause->getAlignment()) {
1134 auto AlignmentCI =
1135 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1136 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001137 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001138 for (auto E : Clause->varlists()) {
1139 unsigned Alignment = ClauseAlignment;
1140 if (Alignment == 0) {
1141 // OpenMP [2.8.1, Description]
1142 // If no optional parameter is specified, implementation-defined default
1143 // alignments for SIMD instructions on the target platforms are assumed.
1144 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001145 CGF.getContext()
1146 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1147 E->getType()->getPointeeType()))
1148 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001149 }
1150 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1151 "alignment is not power of 2");
1152 if (Alignment != 0) {
1153 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1154 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1155 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001156 }
1157 }
1158}
1159
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001160static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001161 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001162 ArrayRef<Expr *> Counters,
1163 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001164 if (!CGF.HaveInsertPoint())
1165 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001166 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001167 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001168 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1169 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001170 Address Addr = Address::invalid();
1171 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001172 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001173 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001174 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001175 Addr = VarEmission.getAllocatedAddress();
1176 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001177 });
John McCall7f416cc2015-09-08 08:05:57 +00001178 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001179 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001180 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001181}
1182
Alexey Bataev62dbb972015-04-22 11:59:37 +00001183static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1184 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1185 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001186 if (!CGF.HaveInsertPoint())
1187 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001188 {
1189 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001190 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1191 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001192 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001193 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001194 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001195 CGF.EmitIgnoredExpr(I);
1196 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001197 }
1198 // Check that loop is executed at least one time.
1199 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1200}
1201
Alexander Musman3276a272015-03-21 10:12:56 +00001202static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001203emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001204 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001205 if (!CGF.HaveInsertPoint())
1206 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001207 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001208 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001209 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001210 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1211 auto *PrivateVD =
1212 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001213 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001214 // Emit private VarDecl with copy init.
1215 CGF.EmitVarDecl(*PrivateVD);
1216 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001217 });
1218 assert(IsRegistered && "linear var already registered as private");
1219 // Silence the warning about unused variable.
1220 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001221 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001222 }
1223 }
1224}
1225
Alexey Bataev45bfad52015-08-21 12:19:04 +00001226static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001227 const OMPExecutableDirective &D,
1228 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001229 if (!CGF.HaveInsertPoint())
1230 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001231 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001232 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1233 /*ignoreResult=*/true);
1234 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1235 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1236 // In presence of finite 'safelen', it may be unsafe to mark all
1237 // the memory instructions parallel, because loop-carried
1238 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001239 if (!IsMonotonic)
1240 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001241 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001242 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1243 /*ignoreResult=*/true);
1244 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001245 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001246 // In presence of finite 'safelen', it may be unsafe to mark all
1247 // the memory instructions parallel, because loop-carried
1248 // dependences of 'safelen' iterations are possible.
1249 CGF.LoopStack.setParallel(false);
1250 }
1251}
1252
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001253void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1254 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001255 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001256 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001257 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001258 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001259}
1260
1261void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001262 if (!HaveInsertPoint())
1263 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001264 auto IC = D.counters().begin();
1265 for (auto F : D.finals()) {
1266 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001267 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001268 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1269 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1270 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001271 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001272 OMPPrivateScope VarScope(*this);
1273 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001274 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001275 (void)VarScope.Privatize();
1276 EmitIgnoredExpr(F);
1277 }
1278 ++IC;
1279 }
1280 emitLinearClauseFinal(*this, D);
1281}
1282
Alexander Musman515ad8c2014-05-22 08:54:05 +00001283void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001284 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001285 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001286 // for (IV in 0..LastIteration) BODY;
1287 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001288 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001289 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001290
Alexey Bataev62dbb972015-04-22 11:59:37 +00001291 // Emit: if (PreCond) - begin.
1292 // If the condition constant folds and can be elided, avoid emitting the
1293 // whole loop.
1294 bool CondConstant;
1295 llvm::BasicBlock *ContBlock = nullptr;
1296 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1297 if (!CondConstant)
1298 return;
1299 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001300 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1301 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001302 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1303 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001304 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001305 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001306 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001307
1308 // Emit the loop iteration variable.
1309 const Expr *IVExpr = S.getIterationVariable();
1310 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1311 CGF.EmitVarDecl(*IVDecl);
1312 CGF.EmitIgnoredExpr(S.getInit());
1313
1314 // Emit the iterations count variable.
1315 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001316 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001317 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1318 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1319 // Emit calculation of the iterations count.
1320 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001321 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001322
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001323 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001324
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001325 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001326 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001327 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001328 {
1329 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001330 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1331 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001332 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001333 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001334 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001335 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001336 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001337 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1338 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001339 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001340 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001341 CGF.EmitStopPoint(&S);
1342 },
1343 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001344 // Emit final copy of the lastprivate variables at the end of loops.
1345 if (HasLastprivateClause) {
1346 CGF.EmitOMPLastprivateClauseFinal(S);
1347 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001348 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001349 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001350 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001351 // Emit: if (PreCond) - end.
1352 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001353 CGF.EmitBranch(ContBlock);
1354 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001355 }
1356 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001357 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001358}
1359
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001360void CodeGenFunction::EmitOMPForOuterLoop(
1361 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1362 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1363 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001364 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001365
1366 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001367 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001368
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001369 assert((Ordered ||
1370 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001371 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001372
1373 // Emit outer loop.
1374 //
1375 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001376 // When schedule(dynamic,chunk_size) is specified, the iterations are
1377 // distributed to threads in the team in chunks as the threads request them.
1378 // Each thread executes a chunk of iterations, then requests another chunk,
1379 // until no chunks remain to be distributed. Each chunk contains chunk_size
1380 // iterations, except for the last chunk to be distributed, which may have
1381 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1382 //
1383 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1384 // to threads in the team in chunks as the executing threads request them.
1385 // Each thread executes a chunk of iterations, then requests another chunk,
1386 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1387 // each chunk is proportional to the number of unassigned iterations divided
1388 // by the number of threads in the team, decreasing to 1. For a chunk_size
1389 // with value k (greater than 1), the size of each chunk is determined in the
1390 // same way, with the restriction that the chunks do not contain fewer than k
1391 // iterations (except for the last chunk to be assigned, which may have fewer
1392 // than k iterations).
1393 //
1394 // When schedule(auto) is specified, the decision regarding scheduling is
1395 // delegated to the compiler and/or runtime system. The programmer gives the
1396 // implementation the freedom to choose any possible mapping of iterations to
1397 // threads in the team.
1398 //
1399 // When schedule(runtime) is specified, the decision regarding scheduling is
1400 // deferred until run time, and the schedule and chunk size are taken from the
1401 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1402 // implementation defined
1403 //
1404 // while(__kmpc_dispatch_next(&LB, &UB)) {
1405 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001406 // while (idx <= UB) { BODY; ++idx;
1407 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1408 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001409 // }
1410 //
1411 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001412 // When schedule(static, chunk_size) is specified, iterations are divided into
1413 // chunks of size chunk_size, and the chunks are assigned to the threads in
1414 // the team in a round-robin fashion in the order of the thread number.
1415 //
1416 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1417 // while (idx <= UB) { BODY; ++idx; } // inner loop
1418 // LB = LB + ST;
1419 // UB = UB + ST;
1420 // }
1421 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001422
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001423 const Expr *IVExpr = S.getIterationVariable();
1424 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1425 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1426
John McCall7f416cc2015-09-08 08:05:57 +00001427 if (DynamicOrOrdered) {
1428 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1429 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1430 IVSize, IVSigned, Ordered, UBVal, Chunk);
1431 } else {
1432 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1433 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1434 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001435
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001436 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1437
1438 // Start the loop with a block that tests the condition.
1439 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1440 EmitBlock(CondBlock);
1441 LoopStack.push(CondBlock);
1442
1443 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001444 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001445 // UB = min(UB, GlobalUB)
1446 EmitIgnoredExpr(S.getEnsureUpperBound());
1447 // IV = LB
1448 EmitIgnoredExpr(S.getInit());
1449 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001450 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001451 } else {
1452 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1453 IL, LB, UB, ST);
1454 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001455
1456 // If there are any cleanups between here and the loop-exit scope,
1457 // create a block to stage a loop exit along.
1458 auto ExitBlock = LoopExit.getBlock();
1459 if (LoopScope.requiresCleanups())
1460 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1461
1462 auto LoopBody = createBasicBlock("omp.dispatch.body");
1463 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1464 if (ExitBlock != LoopExit.getBlock()) {
1465 EmitBlock(ExitBlock);
1466 EmitBranchThroughCleanup(LoopExit);
1467 }
1468 EmitBlock(LoopBody);
1469
Alexander Musman92bdaab2015-03-12 13:37:50 +00001470 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1471 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001472 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001473 EmitIgnoredExpr(S.getInit());
1474
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001475 // Create a block for the increment.
1476 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1477 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1478
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001479 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1480 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001481 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1482 LoopStack.setParallel(!IsMonotonic);
1483 else
1484 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001485
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001486 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001487 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1488 [&S, LoopExit](CodeGenFunction &CGF) {
1489 CGF.EmitOMPLoopBody(S, LoopExit);
1490 CGF.EmitStopPoint(&S);
1491 },
1492 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1493 if (Ordered) {
1494 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1495 CGF, Loc, IVSize, IVSigned);
1496 }
1497 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001498
1499 EmitBlock(Continue.getBlock());
1500 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001501 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001502 // Emit "LB = LB + Stride", "UB = UB + Stride".
1503 EmitIgnoredExpr(S.getNextLowerBound());
1504 EmitIgnoredExpr(S.getNextUpperBound());
1505 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001506
1507 EmitBranch(CondBlock);
1508 LoopStack.pop();
1509 // Emit the fall-through block.
1510 EmitBlock(LoopExit.getBlock());
1511
1512 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001513 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001514 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001515}
1516
Alexander Musmanc6388682014-12-15 07:07:06 +00001517/// \brief Emit a helper variable and return corresponding lvalue.
1518static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1519 const DeclRefExpr *Helper) {
1520 auto VDecl = cast<VarDecl>(Helper->getDecl());
1521 CGF.EmitVarDecl(*VDecl);
1522 return CGF.EmitLValue(Helper);
1523}
1524
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001525namespace {
1526 struct ScheduleKindModifiersTy {
1527 OpenMPScheduleClauseKind Kind;
1528 OpenMPScheduleClauseModifier M1;
1529 OpenMPScheduleClauseModifier M2;
1530 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1531 OpenMPScheduleClauseModifier M1,
1532 OpenMPScheduleClauseModifier M2)
1533 : Kind(Kind), M1(M1), M2(M2) {}
1534 };
1535} // namespace
1536
Alexey Bataev38e89532015-04-16 04:54:05 +00001537bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001538 // Emit the loop iteration variable.
1539 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1540 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1541 EmitVarDecl(*IVDecl);
1542
1543 // Emit the iterations count variable.
1544 // If it is not a variable, Sema decided to calculate iterations count on each
1545 // iteration (e.g., it is foldable into a constant).
1546 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1547 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1548 // Emit calculation of the iterations count.
1549 EmitIgnoredExpr(S.getCalcLastIteration());
1550 }
1551
1552 auto &RT = CGM.getOpenMPRuntime();
1553
Alexey Bataev38e89532015-04-16 04:54:05 +00001554 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001555 // Check pre-condition.
1556 {
1557 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001558 // If the condition constant folds and can be elided, avoid emitting the
1559 // whole loop.
1560 bool CondConstant;
1561 llvm::BasicBlock *ContBlock = nullptr;
1562 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1563 if (!CondConstant)
1564 return false;
1565 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001566 auto *ThenBlock = createBasicBlock("omp.precond.then");
1567 ContBlock = createBasicBlock("omp.precond.end");
1568 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001569 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001570 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001571 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001572 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001573
1574 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001575 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001576 // Emit 'then' code.
1577 {
1578 // Emit helper vars inits.
1579 LValue LB =
1580 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1581 LValue UB =
1582 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1583 LValue ST =
1584 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1585 LValue IL =
1586 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1587
1588 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001589 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1590 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001591 // initialization of firstprivate variables and post-update of
1592 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001593 CGM.getOpenMPRuntime().emitBarrierCall(
1594 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1595 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001596 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001597 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001598 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001599 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001600 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1601 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001602 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001603 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001604
1605 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001606 llvm::Value *Chunk = nullptr;
1607 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1608 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1609 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1610 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1611 ScheduleKind = C->getScheduleKind();
1612 M1 = C->getFirstScheduleModifier();
1613 M2 = C->getSecondScheduleModifier();
1614 if (const auto *Ch = C->getChunkSize()) {
1615 Chunk = EmitScalarExpr(Ch);
1616 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1617 S.getIterationVariable()->getType(),
1618 S.getLocStart());
1619 }
1620 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001621 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1622 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001623 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001624 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1625 // If the static schedule kind is specified or if the ordered clause is
1626 // specified, and if no monotonic modifier is specified, the effect will
1627 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001628 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001629 /* Chunked */ Chunk != nullptr) &&
1630 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001631 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1632 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001633 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1634 // When no chunk_size is specified, the iteration space is divided into
1635 // chunks that are approximately equal in size, and at most one chunk is
1636 // distributed to each thread. Note that the size of the chunks is
1637 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001638 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1639 IVSize, IVSigned, Ordered,
1640 IL.getAddress(), LB.getAddress(),
1641 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001642 auto LoopExit =
1643 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001644 // UB = min(UB, GlobalUB);
1645 EmitIgnoredExpr(S.getEnsureUpperBound());
1646 // IV = LB;
1647 EmitIgnoredExpr(S.getInit());
1648 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001649 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1650 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001651 [&S, LoopExit](CodeGenFunction &CGF) {
1652 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001653 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001654 },
1655 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001656 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001657 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001658 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001659 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001660 const bool IsMonotonic = Ordered ||
1661 ScheduleKind == OMPC_SCHEDULE_static ||
1662 ScheduleKind == OMPC_SCHEDULE_unknown ||
1663 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1664 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001665 // Emit the outer loop, which requests its work chunk [LB..UB] from
1666 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001667 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001668 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1669 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001670 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001671 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001672 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1673 if (HasLastprivateClause)
1674 EmitOMPLastprivateClauseFinal(
1675 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001676 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001677 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1678 EmitOMPSimdFinal(S);
1679 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001680 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001681 if (ContBlock) {
1682 EmitBranch(ContBlock);
1683 EmitBlock(ContBlock, true);
1684 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001685 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001686 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001687}
1688
1689void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001690 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001691 {
1692 OMPLexicalScope Scope(*this, S);
1693 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1694 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1695 };
1696 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1697 S.hasCancel());
1698 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001699
1700 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001701 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001702 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1703 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001704}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001705
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001706void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001707 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001708 {
1709 OMPLexicalScope Scope(*this, S);
1710 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1711 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1712 };
1713 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1714 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001715
1716 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001717 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001718 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1719 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001720}
1721
Alexey Bataev2df54a02015-03-12 08:53:29 +00001722static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1723 const Twine &Name,
1724 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001725 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001726 if (Init)
1727 CGF.EmitScalarInit(Init, LVal);
1728 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001729}
1730
Alexey Bataev3392d762016-02-16 11:18:12 +00001731void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001732 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1733 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001734 bool HasLastprivates = false;
1735 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1736 auto &C = CGF.CGM.getContext();
1737 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1738 // Emit helper vars inits.
1739 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1740 CGF.Builder.getInt32(0));
1741 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1742 : CGF.Builder.getInt32(0);
1743 LValue UB =
1744 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1745 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1746 CGF.Builder.getInt32(1));
1747 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1748 CGF.Builder.getInt32(0));
1749 // Loop counter.
1750 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1751 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1752 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1753 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1754 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1755 // Generate condition for loop.
1756 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1757 OK_Ordinary, S.getLocStart(),
1758 /*fpContractable=*/false);
1759 // Increment for loop counter.
1760 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1761 S.getLocStart());
1762 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1763 // Iterate through all sections and emit a switch construct:
1764 // switch (IV) {
1765 // case 0:
1766 // <SectionStmt[0]>;
1767 // break;
1768 // ...
1769 // case <NumSection> - 1:
1770 // <SectionStmt[<NumSection> - 1]>;
1771 // break;
1772 // }
1773 // .omp.sections.exit:
1774 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1775 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1776 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1777 CS == nullptr ? 1 : CS->size());
1778 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001779 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001780 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001781 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1782 CGF.EmitBlock(CaseBB);
1783 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001784 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001785 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001786 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001787 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001788 } else {
1789 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1790 CGF.EmitBlock(CaseBB);
1791 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1792 CGF.EmitStmt(Stmt);
1793 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001794 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001795 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001796 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001797
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001798 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1799 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001800 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001801 // initialization of firstprivate variables and post-update of lastprivate
1802 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001803 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1804 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1805 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001806 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001807 CGF.EmitOMPPrivateClause(S, LoopScope);
1808 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1809 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1810 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001811
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001812 // Emit static non-chunked loop.
1813 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1814 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1815 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1816 UB.getAddress(), ST.getAddress());
1817 // UB = min(UB, GlobalUB);
1818 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1819 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1820 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1821 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1822 // IV = LB;
1823 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1824 // while (idx <= UB) { BODY; ++idx; }
1825 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1826 [](CodeGenFunction &) {});
1827 // Tell the runtime we are done.
1828 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1829 CGF.EmitOMPReductionClauseFinal(S);
1830
1831 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1832 if (HasLastprivates)
1833 CGF.EmitOMPLastprivateClauseFinal(
1834 S, CGF.Builder.CreateIsNotNull(
1835 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001836 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001837
1838 bool HasCancel = false;
1839 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1840 HasCancel = OSD->hasCancel();
1841 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1842 HasCancel = OPSD->hasCancel();
1843 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1844 HasCancel);
1845 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1846 // clause. Otherwise the barrier will be generated by the codegen for the
1847 // directive.
1848 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001849 // Emit implicit barrier to synchronize threads and avoid data races on
1850 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001851 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1852 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001853 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001854}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001855
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001856void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001857 {
1858 OMPLexicalScope Scope(*this, S);
1859 EmitSections(S);
1860 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001861 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001862 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001863 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1864 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001865 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001866}
1867
1868void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001869 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001870 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1871 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001872 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001873 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1874 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001875}
1876
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001877void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001878 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001879 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001880 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001881 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001882 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001883 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001884 // Build a list of copyprivate variables along with helper expressions
1885 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001886 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001887 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001888 DestExprs.append(C->destination_exprs().begin(),
1889 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001890 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001891 AssignmentOps.append(C->assignment_ops().begin(),
1892 C->assignment_ops().end());
1893 }
Alexey Bataev3392d762016-02-16 11:18:12 +00001894 {
1895 OMPLexicalScope Scope(*this, S);
1896 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00001897 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001898 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00001899 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00001900 CGF.EmitOMPPrivateClause(S, SingleScope);
1901 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00001902 CGF.EmitStmt(
1903 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1904 };
1905 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1906 CopyprivateVars, DestExprs,
1907 SrcExprs, AssignmentOps);
1908 }
1909 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1910 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00001911 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00001912 CGM.getOpenMPRuntime().emitBarrierCall(
1913 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001914 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001915 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001916}
1917
Alexey Bataev8d690652014-12-04 07:23:53 +00001918void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001919 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001920 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1921 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001922 };
1923 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001924}
1925
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001926void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001927 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001928 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1929 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001930 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001931 Expr *Hint = nullptr;
1932 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1933 Hint = HintClause->getHint();
1934 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1935 S.getDirectiveName().getAsString(),
1936 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001937}
1938
Alexey Bataev671605e2015-04-13 05:28:11 +00001939void CodeGenFunction::EmitOMPParallelForDirective(
1940 const OMPParallelForDirective &S) {
1941 // Emit directive as a combined directive that consists of two implicit
1942 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001943 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001944 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1945 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001946 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001947 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001948}
1949
Alexander Musmane4e893b2014-09-23 09:33:00 +00001950void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001951 const OMPParallelForSimdDirective &S) {
1952 // Emit directive as a combined directive that consists of two implicit
1953 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001954 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001955 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1956 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001957 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001958 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001959}
1960
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001961void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001962 const OMPParallelSectionsDirective &S) {
1963 // Emit directive as a combined directive that consists of two implicit
1964 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001965 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00001966 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001967 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001968}
1969
Alexey Bataev62b63b12015-03-10 07:28:44 +00001970void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1971 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00001972 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001973 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1974 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1975 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001976 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001977 // The first function argument for tasks is a thread id, the second one is a
1978 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001979 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1980 // Get list of private variables.
1981 llvm::SmallVector<const Expr *, 8> PrivateVars;
1982 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001983 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001984 auto IRef = C->varlist_begin();
1985 for (auto *IInit : C->private_copies()) {
1986 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1987 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1988 PrivateVars.push_back(*IRef);
1989 PrivateCopies.push_back(IInit);
1990 }
1991 ++IRef;
1992 }
1993 }
1994 EmittedAsPrivate.clear();
1995 // Get list of firstprivate variables.
1996 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1997 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1998 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001999 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002000 auto IRef = C->varlist_begin();
2001 auto IElemInitRef = C->inits().begin();
2002 for (auto *IInit : C->private_copies()) {
2003 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2004 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2005 FirstprivateVars.push_back(*IRef);
2006 FirstprivateCopies.push_back(IInit);
2007 FirstprivateInits.push_back(*IElemInitRef);
2008 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002009 ++IRef;
2010 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002011 }
2012 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002013 // Build list of dependences.
2014 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2015 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002016 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002017 for (auto *IRef : C->varlists()) {
2018 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2019 }
2020 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002021 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2022 CodeGenFunction &CGF) {
2023 // Set proper addresses for generated private copies.
2024 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2025 OMPPrivateScope Scope(CGF);
2026 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002027 auto *CopyFn = CGF.Builder.CreateLoad(
2028 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2029 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2030 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002031 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002032 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002033 PrivatePtrs;
2034 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2035 CallArgs.push_back(PrivatesPtr);
2036 for (auto *E : PrivateVars) {
2037 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002038 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002039 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2040 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002041 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002042 }
2043 for (auto *E : FirstprivateVars) {
2044 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002045 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002046 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2047 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002048 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002049 }
2050 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2051 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002052 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2053 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002054 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2055 }
2056 }
2057 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002058 if (*PartId) {
2059 // TODO: emit code for untied tasks.
2060 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002061 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002062 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002063 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2064 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002065 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002066 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002067 // Check if the task is final
2068 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002069 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002070 // If the condition constant folds and can be elided, try to avoid emitting
2071 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002072 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002073 bool CondConstant;
2074 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2075 Final.setInt(CondConstant);
2076 else
2077 Final.setPointer(EvaluateExprAsBool(Cond));
2078 } else {
2079 // By default the task is not final.
2080 Final.setInt(/*IntVal=*/false);
2081 }
2082 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002083 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002084 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2085 if (C->getNameModifier() == OMPD_unknown ||
2086 C->getNameModifier() == OMPD_task) {
2087 IfCond = C->getCondition();
2088 break;
2089 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002090 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002091 CGM.getOpenMPRuntime().emitTaskCall(
2092 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002093 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002094 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002095}
2096
Alexey Bataev9f797f32015-02-05 05:57:51 +00002097void CodeGenFunction::EmitOMPTaskyieldDirective(
2098 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002099 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002100}
2101
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002102void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002103 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002104}
2105
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002106void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2107 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002108}
2109
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002110void CodeGenFunction::EmitOMPTaskgroupDirective(
2111 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002112 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002113 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2114 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002115 };
2116 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2117}
2118
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002119void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002120 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002121 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002122 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2123 FlushClause->varlist_end());
2124 }
2125 return llvm::None;
2126 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002127}
2128
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002129void CodeGenFunction::EmitOMPDistributeDirective(
2130 const OMPDistributeDirective &S) {
2131 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2132}
2133
Alexey Bataev5f600d62015-09-29 03:48:57 +00002134static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2135 const CapturedStmt *S) {
2136 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2137 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2138 CGF.CapturedStmtInfo = &CapStmtInfo;
2139 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2140 Fn->addFnAttr(llvm::Attribute::NoInline);
2141 return Fn;
2142}
2143
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002144void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002145 if (!S.getAssociatedStmt())
2146 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002147 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002148 auto *C = S.getSingleClause<OMPSIMDClause>();
2149 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2150 if (C) {
2151 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2152 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2153 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2154 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2155 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2156 } else {
2157 CGF.EmitStmt(
2158 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2159 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002160 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002161 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002162}
2163
Alexey Bataevb57056f2015-01-22 06:17:56 +00002164static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002165 QualType SrcType, QualType DestType,
2166 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002167 assert(CGF.hasScalarEvaluationKind(DestType) &&
2168 "DestType must have scalar evaluation kind.");
2169 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2170 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002171 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2172 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002173 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002174 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002175}
2176
2177static CodeGenFunction::ComplexPairTy
2178convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002179 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002180 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2181 "DestType must have complex evaluation kind.");
2182 CodeGenFunction::ComplexPairTy ComplexVal;
2183 if (Val.isScalar()) {
2184 // Convert the input element to the element type of the complex.
2185 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002186 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2187 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002188 ComplexVal = CodeGenFunction::ComplexPairTy(
2189 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2190 } else {
2191 assert(Val.isComplex() && "Must be a scalar or complex.");
2192 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2193 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2194 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002195 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002196 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002197 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002198 }
2199 return ComplexVal;
2200}
2201
Alexey Bataev5e018f92015-04-23 06:35:10 +00002202static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2203 LValue LVal, RValue RVal) {
2204 if (LVal.isGlobalReg()) {
2205 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2206 } else {
2207 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2208 : llvm::Monotonic,
2209 LVal.isVolatile(), /*IsInit=*/false);
2210 }
2211}
2212
Alexey Bataev8524d152016-01-21 12:35:58 +00002213void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2214 QualType RValTy, SourceLocation Loc) {
2215 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002216 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002217 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2218 *this, RVal, RValTy, LVal.getType(), Loc)),
2219 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002220 break;
2221 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002222 EmitStoreOfComplex(
2223 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002224 /*isInit=*/false);
2225 break;
2226 case TEK_Aggregate:
2227 llvm_unreachable("Must be a scalar or complex.");
2228 }
2229}
2230
Alexey Bataevb57056f2015-01-22 06:17:56 +00002231static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2232 const Expr *X, const Expr *V,
2233 SourceLocation Loc) {
2234 // v = x;
2235 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2236 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2237 LValue XLValue = CGF.EmitLValue(X);
2238 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002239 RValue Res = XLValue.isGlobalReg()
2240 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2241 : CGF.EmitAtomicLoad(XLValue, Loc,
2242 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002243 : llvm::Monotonic,
2244 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002245 // OpenMP, 2.12.6, atomic Construct
2246 // Any atomic construct with a seq_cst clause forces the atomically
2247 // performed operation to include an implicit flush operation without a
2248 // list.
2249 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002250 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002251 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002252}
2253
Alexey Bataevb8329262015-02-27 06:33:30 +00002254static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2255 const Expr *X, const Expr *E,
2256 SourceLocation Loc) {
2257 // x = expr;
2258 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002259 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002260 // OpenMP, 2.12.6, atomic Construct
2261 // Any atomic construct with a seq_cst clause forces the atomically
2262 // performed operation to include an implicit flush operation without a
2263 // list.
2264 if (IsSeqCst)
2265 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2266}
2267
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002268static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2269 RValue Update,
2270 BinaryOperatorKind BO,
2271 llvm::AtomicOrdering AO,
2272 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002273 auto &Context = CGF.CGM.getContext();
2274 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002275 // expression is simple and atomic is allowed for the given type for the
2276 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002277 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002278 !Update.getScalarVal()->getType()->isIntegerTy() ||
2279 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2280 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002281 X.getAddress().getElementType())) ||
2282 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002283 !Context.getTargetInfo().hasBuiltinAtomic(
2284 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002285 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002286
2287 llvm::AtomicRMWInst::BinOp RMWOp;
2288 switch (BO) {
2289 case BO_Add:
2290 RMWOp = llvm::AtomicRMWInst::Add;
2291 break;
2292 case BO_Sub:
2293 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002294 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002295 RMWOp = llvm::AtomicRMWInst::Sub;
2296 break;
2297 case BO_And:
2298 RMWOp = llvm::AtomicRMWInst::And;
2299 break;
2300 case BO_Or:
2301 RMWOp = llvm::AtomicRMWInst::Or;
2302 break;
2303 case BO_Xor:
2304 RMWOp = llvm::AtomicRMWInst::Xor;
2305 break;
2306 case BO_LT:
2307 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2308 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2309 : llvm::AtomicRMWInst::Max)
2310 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2311 : llvm::AtomicRMWInst::UMax);
2312 break;
2313 case BO_GT:
2314 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2315 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2316 : llvm::AtomicRMWInst::Min)
2317 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2318 : llvm::AtomicRMWInst::UMin);
2319 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002320 case BO_Assign:
2321 RMWOp = llvm::AtomicRMWInst::Xchg;
2322 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002323 case BO_Mul:
2324 case BO_Div:
2325 case BO_Rem:
2326 case BO_Shl:
2327 case BO_Shr:
2328 case BO_LAnd:
2329 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002330 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002331 case BO_PtrMemD:
2332 case BO_PtrMemI:
2333 case BO_LE:
2334 case BO_GE:
2335 case BO_EQ:
2336 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002337 case BO_AddAssign:
2338 case BO_SubAssign:
2339 case BO_AndAssign:
2340 case BO_OrAssign:
2341 case BO_XorAssign:
2342 case BO_MulAssign:
2343 case BO_DivAssign:
2344 case BO_RemAssign:
2345 case BO_ShlAssign:
2346 case BO_ShrAssign:
2347 case BO_Comma:
2348 llvm_unreachable("Unsupported atomic update operation");
2349 }
2350 auto *UpdateVal = Update.getScalarVal();
2351 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2352 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002353 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002354 X.getType()->hasSignedIntegerRepresentation());
2355 }
John McCall7f416cc2015-09-08 08:05:57 +00002356 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002357 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002358}
2359
Alexey Bataev5e018f92015-04-23 06:35:10 +00002360std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002361 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2362 llvm::AtomicOrdering AO, SourceLocation Loc,
2363 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2364 // Update expressions are allowed to have the following forms:
2365 // x binop= expr; -> xrval + expr;
2366 // x++, ++x -> xrval + 1;
2367 // x--, --x -> xrval - 1;
2368 // x = x binop expr; -> xrval binop expr
2369 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002370 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2371 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002372 if (X.isGlobalReg()) {
2373 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2374 // 'xrval'.
2375 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2376 } else {
2377 // Perform compare-and-swap procedure.
2378 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002379 }
2380 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002381 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002382}
2383
2384static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2385 const Expr *X, const Expr *E,
2386 const Expr *UE, bool IsXLHSInRHSPart,
2387 SourceLocation Loc) {
2388 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2389 "Update expr in 'atomic update' must be a binary operator.");
2390 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2391 // Update expressions are allowed to have the following forms:
2392 // x binop= expr; -> xrval + expr;
2393 // x++, ++x -> xrval + 1;
2394 // x--, --x -> xrval - 1;
2395 // x = x binop expr; -> xrval binop expr
2396 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002397 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002398 LValue XLValue = CGF.EmitLValue(X);
2399 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002400 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002401 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2402 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2403 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2404 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2405 auto Gen =
2406 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2407 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2408 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2409 return CGF.EmitAnyExpr(UE);
2410 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002411 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2412 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2413 // OpenMP, 2.12.6, atomic Construct
2414 // Any atomic construct with a seq_cst clause forces the atomically
2415 // performed operation to include an implicit flush operation without a
2416 // list.
2417 if (IsSeqCst)
2418 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2419}
2420
2421static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002422 QualType SourceType, QualType ResType,
2423 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002424 switch (CGF.getEvaluationKind(ResType)) {
2425 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002426 return RValue::get(
2427 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002428 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002429 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002430 return RValue::getComplex(Res.first, Res.second);
2431 }
2432 case TEK_Aggregate:
2433 break;
2434 }
2435 llvm_unreachable("Must be a scalar or complex.");
2436}
2437
2438static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2439 bool IsPostfixUpdate, const Expr *V,
2440 const Expr *X, const Expr *E,
2441 const Expr *UE, bool IsXLHSInRHSPart,
2442 SourceLocation Loc) {
2443 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2444 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2445 RValue NewVVal;
2446 LValue VLValue = CGF.EmitLValue(V);
2447 LValue XLValue = CGF.EmitLValue(X);
2448 RValue ExprRValue = CGF.EmitAnyExpr(E);
2449 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2450 QualType NewVValType;
2451 if (UE) {
2452 // 'x' is updated with some additional value.
2453 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2454 "Update expr in 'atomic capture' must be a binary operator.");
2455 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2456 // Update expressions are allowed to have the following forms:
2457 // x binop= expr; -> xrval + expr;
2458 // x++, ++x -> xrval + 1;
2459 // x--, --x -> xrval - 1;
2460 // x = x binop expr; -> xrval binop expr
2461 // x = expr Op x; - > expr binop xrval;
2462 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2463 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2464 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2465 NewVValType = XRValExpr->getType();
2466 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2467 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2468 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2469 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2470 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2471 RValue Res = CGF.EmitAnyExpr(UE);
2472 NewVVal = IsPostfixUpdate ? XRValue : Res;
2473 return Res;
2474 };
2475 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2476 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2477 if (Res.first) {
2478 // 'atomicrmw' instruction was generated.
2479 if (IsPostfixUpdate) {
2480 // Use old value from 'atomicrmw'.
2481 NewVVal = Res.second;
2482 } else {
2483 // 'atomicrmw' does not provide new value, so evaluate it using old
2484 // value of 'x'.
2485 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2486 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2487 NewVVal = CGF.EmitAnyExpr(UE);
2488 }
2489 }
2490 } else {
2491 // 'x' is simply rewritten with some 'expr'.
2492 NewVValType = X->getType().getNonReferenceType();
2493 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002494 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002495 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2496 NewVVal = XRValue;
2497 return ExprRValue;
2498 };
2499 // Try to perform atomicrmw xchg, otherwise simple exchange.
2500 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2501 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2502 Loc, Gen);
2503 if (Res.first) {
2504 // 'atomicrmw' instruction was generated.
2505 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2506 }
2507 }
2508 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002509 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002510 // OpenMP, 2.12.6, atomic Construct
2511 // Any atomic construct with a seq_cst clause forces the atomically
2512 // performed operation to include an implicit flush operation without a
2513 // list.
2514 if (IsSeqCst)
2515 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2516}
2517
Alexey Bataevb57056f2015-01-22 06:17:56 +00002518static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002519 bool IsSeqCst, bool IsPostfixUpdate,
2520 const Expr *X, const Expr *V, const Expr *E,
2521 const Expr *UE, bool IsXLHSInRHSPart,
2522 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002523 switch (Kind) {
2524 case OMPC_read:
2525 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2526 break;
2527 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002528 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2529 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002530 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002531 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002532 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2533 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002534 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002535 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2536 IsXLHSInRHSPart, Loc);
2537 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002538 case OMPC_if:
2539 case OMPC_final:
2540 case OMPC_num_threads:
2541 case OMPC_private:
2542 case OMPC_firstprivate:
2543 case OMPC_lastprivate:
2544 case OMPC_reduction:
2545 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002546 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002547 case OMPC_collapse:
2548 case OMPC_default:
2549 case OMPC_seq_cst:
2550 case OMPC_shared:
2551 case OMPC_linear:
2552 case OMPC_aligned:
2553 case OMPC_copyin:
2554 case OMPC_copyprivate:
2555 case OMPC_flush:
2556 case OMPC_proc_bind:
2557 case OMPC_schedule:
2558 case OMPC_ordered:
2559 case OMPC_nowait:
2560 case OMPC_untied:
2561 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002562 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002563 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002564 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002565 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002566 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002567 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002568 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002569 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002570 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002571 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002572 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002573 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002574 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002575 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002576 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002577 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2578 }
2579}
2580
2581void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002582 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002583 OpenMPClauseKind Kind = OMPC_unknown;
2584 for (auto *C : S.clauses()) {
2585 // Find first clause (skip seq_cst clause, if it is first).
2586 if (C->getClauseKind() != OMPC_seq_cst) {
2587 Kind = C->getClauseKind();
2588 break;
2589 }
2590 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002591
2592 const auto *CS =
2593 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002594 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002595 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002596 }
2597 // Processing for statements under 'atomic capture'.
2598 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2599 for (const auto *C : Compound->body()) {
2600 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2601 enterFullExpression(EWC);
2602 }
2603 }
2604 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002605
Alexey Bataev3392d762016-02-16 11:18:12 +00002606 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002607 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2608 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002609 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2610 S.getV(), S.getExpr(), S.getUpdateExpr(),
2611 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002612 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002613 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002614}
2615
Samuel Antaobed3c462015-10-02 16:14:20 +00002616void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002617 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002618 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2619
2620 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002621 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002622
Samuel Antaoee8fb302016-01-06 13:42:12 +00002623 llvm::Function *Fn = nullptr;
2624 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002625
2626 // Check if we have any if clause associated with the directive.
2627 const Expr *IfCond = nullptr;
2628
2629 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2630 IfCond = C->getCondition();
2631 }
2632
2633 // Check if we have any device clause associated with the directive.
2634 const Expr *Device = nullptr;
2635 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2636 Device = C->getDevice();
2637 }
2638
Samuel Antaoee8fb302016-01-06 13:42:12 +00002639 // Check if we have an if clause whose conditional always evaluates to false
2640 // or if we do not have any targets specified. If so the target region is not
2641 // an offload entry point.
2642 bool IsOffloadEntry = true;
2643 if (IfCond) {
2644 bool Val;
2645 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2646 IsOffloadEntry = false;
2647 }
2648 if (CGM.getLangOpts().OMPTargetTriples.empty())
2649 IsOffloadEntry = false;
2650
2651 assert(CurFuncDecl && "No parent declaration for target region!");
2652 StringRef ParentName;
2653 // In case we have Ctors/Dtors we use the complete type variant to produce
2654 // the mangling of the device outlined kernel.
2655 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2656 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2657 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2658 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2659 else
2660 ParentName =
2661 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2662
2663 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2664 IsOffloadEntry);
2665
2666 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002667 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002668}
2669
Alexey Bataev13314bf2014-10-09 04:18:56 +00002670void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2671 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2672}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002673
2674void CodeGenFunction::EmitOMPCancellationPointDirective(
2675 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002676 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2677 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002678}
2679
Alexey Bataev80909872015-07-02 11:25:17 +00002680void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002681 const Expr *IfCond = nullptr;
2682 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2683 if (C->getNameModifier() == OMPD_unknown ||
2684 C->getNameModifier() == OMPD_cancel) {
2685 IfCond = C->getCondition();
2686 break;
2687 }
2688 }
2689 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002690 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002691}
2692
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002693CodeGenFunction::JumpDest
2694CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2695 if (Kind == OMPD_parallel || Kind == OMPD_task)
2696 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002697 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002698 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002699 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002700}
Michael Wong65f367f2015-07-21 13:44:28 +00002701
2702// Generate the instructions for '#pragma omp target data' directive.
2703void CodeGenFunction::EmitOMPTargetDataDirective(
2704 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002705 // emit the code inside the construct for now
2706 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002707 CGM.getOpenMPRuntime().emitInlinedDirective(
2708 *this, OMPD_target_data,
2709 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002710}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002711
Samuel Antaodf67fc42016-01-19 19:15:56 +00002712void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2713 const OMPTargetEnterDataDirective &S) {
2714 // TODO: codegen for target enter data.
2715}
2716
Samuel Antao72590762016-01-19 20:04:50 +00002717void CodeGenFunction::EmitOMPTargetExitDataDirective(
2718 const OMPTargetExitDataDirective &S) {
2719 // TODO: codegen for target exit data.
2720}
2721
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002722void CodeGenFunction::EmitOMPTargetParallelDirective(
2723 const OMPTargetParallelDirective &S) {
2724 // TODO: codegen for target parallel.
2725}
2726
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002727void CodeGenFunction::EmitOMPTargetParallelForDirective(
2728 const OMPTargetParallelForDirective &S) {
2729 // TODO: codegen for target parallel for.
2730}
2731
Alexey Bataev49f6e782015-12-01 04:18:41 +00002732void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2733 // emit the code inside the construct for now
2734 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2735 CGM.getOpenMPRuntime().emitInlinedDirective(
2736 *this, OMPD_taskloop,
2737 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2738}
2739
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002740void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2741 const OMPTaskLoopSimdDirective &S) {
2742 // emit the code inside the construct for now
2743 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2744 CGM.getOpenMPRuntime().emitInlinedDirective(
2745 *this, OMPD_taskloop_simd,
2746 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2747}
2748