blob: c5fd7416795367c0d064a1b6c5161c55e21a54a3 [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"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022using namespace clang;
23using namespace CodeGen;
24
Alexey Bataev3392d762016-02-16 11:18:12 +000025namespace {
26/// Lexical scope for OpenMP executable constructs, that handles correct codegen
27/// for captured expressions.
28class OMPLexicalScope {
29 CodeGenFunction::LexicalScope Scope;
30 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
47
Alexey Bataev3392d762016-02-16 11:18:12 +000048public:
49 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
50 : Scope(CGF, S.getSourceRange()) {
51 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000052 }
53};
54} // namespace
55
Alexey Bataev1189bd02016-01-26 12:20:39 +000056llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
57 auto &C = getContext();
58 llvm::Value *Size = nullptr;
59 auto SizeInChars = C.getTypeSizeInChars(Ty);
60 if (SizeInChars.isZero()) {
61 // getTypeSizeInChars() returns 0 for a VLA.
62 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
63 llvm::Value *ArraySize;
64 std::tie(ArraySize, Ty) = getVLASize(VAT);
65 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
66 }
67 SizeInChars = C.getTypeSizeInChars(Ty);
68 if (SizeInChars.isZero())
69 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
70 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
71 } else
72 Size = CGM.getSize(SizeInChars);
73 return Size;
74}
75
Alexey Bataev2377fe92015-09-10 08:12:02 +000076void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000077 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000078 const RecordDecl *RD = S.getCapturedRecordDecl();
79 auto CurField = RD->field_begin();
80 auto CurCap = S.captures().begin();
81 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
82 E = S.capture_init_end();
83 I != E; ++I, ++CurField, ++CurCap) {
84 if (CurField->hasCapturedVLAType()) {
85 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000086 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000087 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000088 } else if (CurCap->capturesThis())
89 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000090 else if (CurCap->capturesVariableByCopy())
91 CapturedVars.push_back(
92 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
93 else {
94 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000095 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000096 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000097 }
98}
99
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000100static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
101 StringRef Name, LValue AddrLV,
102 bool isReferenceType = false) {
103 ASTContext &Ctx = CGF.getContext();
104
105 auto *CastedPtr = CGF.EmitScalarConversion(
106 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
107 Ctx.getPointerType(DstType), SourceLocation());
108 auto TmpAddr =
109 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
110 .getAddress();
111
112 // If we are dealing with references we need to return the address of the
113 // reference instead of the reference of the value.
114 if (isReferenceType) {
115 QualType RefType = Ctx.getLValueReferenceType(DstType);
116 auto *RefVal = TmpAddr.getPointer();
117 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
118 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
119 CGF.EmitScalarInit(RefVal, TmpLVal);
120 }
121
122 return TmpAddr;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 assert(
128 CapturedStmtInfo &&
129 "CapturedStmtInfo should be set when generating the captured function");
130 const CapturedDecl *CD = S.getCapturedDecl();
131 const RecordDecl *RD = S.getCapturedRecordDecl();
132 assert(CD->hasBody() && "missing CapturedDecl body");
133
134 // Build the argument list.
135 ASTContext &Ctx = CGM.getContext();
136 FunctionArgList Args;
137 Args.append(CD->param_begin(),
138 std::next(CD->param_begin(), CD->getContextParamPosition()));
139 auto I = S.captures().begin();
140 for (auto *FD : RD->fields()) {
141 QualType ArgType = FD->getType();
142 IdentifierInfo *II = nullptr;
143 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000144
145 // If this is a capture by copy and the type is not a pointer, the outlined
146 // function argument type should be uintptr and the value properly casted to
147 // uintptr. This is necessary given that the runtime library is only able to
148 // deal with pointers. We can pass in the same way the VLA type sizes to the
149 // outlined function.
150 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
151 I->capturesVariableArrayType())
152 ArgType = Ctx.getUIntPtrType();
153
154 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000155 CapVar = I->getCapturedVar();
156 II = CapVar->getIdentifier();
157 } else if (I->capturesThis())
158 II = &getContext().Idents.get("this");
159 else {
160 assert(I->capturesVariableArrayType());
161 II = &getContext().Idents.get("vla");
162 }
163 if (ArgType->isVariablyModifiedType())
164 ArgType = getContext().getVariableArrayDecayedType(ArgType);
165 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
166 FD->getLocation(), II, ArgType));
167 ++I;
168 }
169 Args.append(
170 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
171 CD->param_end());
172
173 // Create the function declaration.
174 FunctionType::ExtInfo ExtInfo;
175 const CGFunctionInfo &FuncInfo =
176 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
177 /*IsVariadic=*/false);
178 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
179
180 llvm::Function *F = llvm::Function::Create(
181 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
182 CapturedStmtInfo->getHelperName(), &CGM.getModule());
183 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
184 if (CD->isNothrow())
185 F->addFnAttr(llvm::Attribute::NoUnwind);
186
187 // Generate the function.
188 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
189 CD->getBody()->getLocStart());
190 unsigned Cnt = CD->getContextParamPosition();
191 I = S.captures().begin();
192 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000193 // If we are capturing a pointer by copy we don't need to do anything, just
194 // use the value that we get from the arguments.
195 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
196 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000197 ++Cnt;
198 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000199 continue;
200 }
201
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 LValue ArgLVal =
203 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
204 AlignmentSource::Decl);
205 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206 LValue CastedArgLVal =
207 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
208 Args[Cnt]->getName(), ArgLVal),
209 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000210 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000211 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000212 auto VAT = FD->getCapturedVLAType();
213 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
214 } else if (I->capturesVariable()) {
215 auto *Var = I->getCapturedVar();
216 QualType VarTy = Var->getType();
217 Address ArgAddr = ArgLVal.getAddress();
218 if (!VarTy->isReferenceType()) {
219 ArgAddr = EmitLoadOfReference(
220 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
221 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000222 setAddrOfLocalVar(
223 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224 } else if (I->capturesVariableByCopy()) {
225 assert(!FD->getType()->isAnyPointerType() &&
226 "Not expecting a captured pointer.");
227 auto *Var = I->getCapturedVar();
228 QualType VarTy = Var->getType();
229 setAddrOfLocalVar(I->getCapturedVar(),
230 castValueFromUintptr(*this, FD->getType(),
231 Args[Cnt]->getName(), ArgLVal,
232 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 } else {
234 // If 'this' is captured, load it into CXXThisValue.
235 assert(I->capturesThis());
236 CXXThisValue =
237 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
238 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000239 ++Cnt;
240 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000241 }
242
Serge Pavlov3a561452015-12-06 14:32:39 +0000243 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 CapturedStmtInfo->EmitBody(*this, CD->getBody());
245 FinishFunction(CD->getBodyRBrace());
246
247 return F;
248}
249
Alexey Bataev9959db52014-05-06 10:08:46 +0000250//===----------------------------------------------------------------------===//
251// OpenMP Directive Emission
252//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000253void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000254 Address DestAddr, Address SrcAddr, QualType OriginalType,
255 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000256 // Perform element-by-element initialization.
257 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000258
259 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000260 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000261 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
262 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
263
264 auto SrcBegin = SrcAddr.getPointer();
265 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000266 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000267 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
268 // The basic structure here is a while-do loop.
269 auto BodyBB = createBasicBlock("omp.arraycpy.body");
270 auto DoneBB = createBasicBlock("omp.arraycpy.done");
271 auto IsEmpty =
272 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
273 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000274
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 // Enter the loop body, making that address the current address.
276 auto EntryBB = Builder.GetInsertBlock();
277 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000278
279 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
280
281 llvm::PHINode *SrcElementPHI =
282 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
283 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
284 Address SrcElementCurrent =
285 Address(SrcElementPHI,
286 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
287
288 llvm::PHINode *DestElementPHI =
289 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
290 DestElementPHI->addIncoming(DestBegin, EntryBB);
291 Address DestElementCurrent =
292 Address(DestElementPHI,
293 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000294
Alexey Bataev420d45b2015-04-14 05:11:24 +0000295 // Emit copy.
296 CopyGen(DestElementCurrent, SrcElementCurrent);
297
298 // Shift the address forward by one element.
299 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000300 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000301 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000302 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000303 // Check whether we've reached the end.
304 auto Done =
305 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
306 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000307 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
308 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000309
310 // Done.
311 EmitBlock(DoneBB, /*IsFinished=*/true);
312}
313
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000314/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000315/// \param DestAddr Address of the array.
316/// \param Type Type of array.
317/// \param Init Initial expression of array.
318static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
319 QualType Type, const Expr *Init) {
320 // Perform element-by-element initialization.
321 QualType ElementTy;
322
323 // Drill down to the base element type on both arrays.
324 auto ArrayTy = Type->getAsArrayTypeUnsafe();
325 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
326 DestAddr =
327 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
328
329 auto DestBegin = DestAddr.getPointer();
330 // Cast from pointer to array type to pointer to single element.
331 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
332 // The basic structure here is a while-do loop.
333 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
334 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
335 auto IsEmpty =
336 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
337 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
338
339 // Enter the loop body, making that address the current address.
340 auto EntryBB = CGF.Builder.GetInsertBlock();
341 CGF.EmitBlock(BodyBB);
342
343 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
344
345 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
346 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
347 DestElementPHI->addIncoming(DestBegin, EntryBB);
348 Address DestElementCurrent =
349 Address(DestElementPHI,
350 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
351
352 // Emit copy.
353 {
354 CodeGenFunction::RunCleanupsScope InitScope(CGF);
355 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
356 /*IsInitializer=*/false);
357 }
358
359 // Shift the address forward by one element.
360 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
361 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
362 // Check whether we've reached the end.
363 auto Done =
364 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
365 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
366 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
367
368 // Done.
369 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
370}
371
John McCall7f416cc2015-09-08 08:05:57 +0000372void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
373 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000374 const VarDecl *SrcVD, const Expr *Copy) {
375 if (OriginalType->isArrayType()) {
376 auto *BO = dyn_cast<BinaryOperator>(Copy);
377 if (BO && BO->getOpcode() == BO_Assign) {
378 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000379 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000380 } else {
381 // For arrays with complex element types perform element by element
382 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000383 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000384 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000385 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000386 // Working with the single array element, so have to remap
387 // destination and source variables to corresponding array
388 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000389 CodeGenFunction::OMPPrivateScope Remap(*this);
390 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000391 return DestElement;
392 });
393 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000394 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000395 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000396 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000397 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000398 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000399 } else {
400 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000401 CodeGenFunction::OMPPrivateScope Remap(*this);
402 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
403 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000404 (void)Remap.Privatize();
405 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000406 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000407 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000408}
409
Alexey Bataev69c62a92015-04-15 04:52:20 +0000410bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
411 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000412 if (!HaveInsertPoint())
413 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000414 bool FirstprivateIsLastprivate = false;
415 llvm::DenseSet<const VarDecl *> Lastprivates;
416 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
417 for (const auto *D : C->varlists())
418 Lastprivates.insert(
419 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
420 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000421 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000422 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000423 auto IRef = C->varlist_begin();
424 auto InitsRef = C->inits().begin();
425 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000426 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000427 FirstprivateIsLastprivate =
428 FirstprivateIsLastprivate ||
429 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
430 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000431 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
432 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
433 bool IsRegistered;
434 DeclRefExpr DRE(
435 const_cast<VarDecl *>(OrigVD),
436 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
437 OrigVD) != nullptr,
438 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000439 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000440 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000441 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000442 // Emit VarDecl with copy init for arrays.
443 // Get the address of the original variable captured in current
444 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000445 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000446 auto Emission = EmitAutoVarAlloca(*VD);
447 auto *Init = VD->getInit();
448 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
449 // Perform simple memcpy.
450 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000451 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000452 } else {
453 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000454 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000455 [this, VDInit, Init](Address DestElement,
456 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000457 // Clean up any temporaries needed by the initialization.
458 RunCleanupsScope InitScope(*this);
459 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000460 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000461 EmitAnyExprToMem(Init, DestElement,
462 Init->getType().getQualifiers(),
463 /*IsInitializer*/ false);
464 LocalDeclMap.erase(VDInit);
465 });
466 }
467 EmitAutoVarCleanups(Emission);
468 return Emission.getAllocatedAddress();
469 });
470 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000471 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000472 // Emit private VarDecl with copy init.
473 // Remap temp VDInit variable to the address of the original
474 // variable
475 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000476 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 EmitDecl(*VD);
478 LocalDeclMap.erase(VDInit);
479 return GetAddrOfLocalVar(VD);
480 });
481 }
482 assert(IsRegistered &&
483 "firstprivate var already registered as private");
484 // Silence the warning about unused variable.
485 (void)IsRegistered;
486 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000487 ++IRef;
488 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000489 }
490 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000491 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000492}
493
Alexey Bataev03b340a2014-10-21 03:16:40 +0000494void CodeGenFunction::EmitOMPPrivateClause(
495 const OMPExecutableDirective &D,
496 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000497 if (!HaveInsertPoint())
498 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000499 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000500 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000501 auto IRef = C->varlist_begin();
502 for (auto IInit : C->private_copies()) {
503 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000504 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
505 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
506 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000507 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000508 // Emit private VarDecl with copy init.
509 EmitDecl(*VD);
510 return GetAddrOfLocalVar(VD);
511 });
512 assert(IsRegistered && "private var already registered as private");
513 // Silence the warning about unused variable.
514 (void)IsRegistered;
515 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000516 ++IRef;
517 }
518 }
519}
520
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000521bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000522 if (!HaveInsertPoint())
523 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000524 // threadprivate_var1 = master_threadprivate_var1;
525 // operator=(threadprivate_var2, master_threadprivate_var2);
526 // ...
527 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 llvm::DenseSet<const VarDecl *> CopiedVars;
529 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000530 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000531 auto IRef = C->varlist_begin();
532 auto ISrcRef = C->source_exprs().begin();
533 auto IDestRef = C->destination_exprs().begin();
534 for (auto *AssignOp : C->assignment_ops()) {
535 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000536 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000537 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000538 // Get the address of the master variable. If we are emitting code with
539 // TLS support, the address is passed from the master as field in the
540 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000541 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000542 if (getLangOpts().OpenMPUseTLS &&
543 getContext().getTargetInfo().isTLSSupported()) {
544 assert(CapturedStmtInfo->lookup(VD) &&
545 "Copyin threadprivates should have been captured!");
546 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
547 VK_LValue, (*IRef)->getExprLoc());
548 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000549 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000550 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000551 MasterAddr =
552 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
553 : CGM.GetAddrOfGlobal(VD),
554 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000555 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000556 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000557 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000558 if (CopiedVars.size() == 1) {
559 // At first check if current thread is a master thread. If it is, no
560 // need to copy data.
561 CopyBegin = createBasicBlock("copyin.not.master");
562 CopyEnd = createBasicBlock("copyin.not.master.end");
563 Builder.CreateCondBr(
564 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000565 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
566 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000567 CopyBegin, CopyEnd);
568 EmitBlock(CopyBegin);
569 }
570 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
571 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000572 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000573 }
574 ++IRef;
575 ++ISrcRef;
576 ++IDestRef;
577 }
578 }
579 if (CopyEnd) {
580 // Exit out of copying procedure for non-master thread.
581 EmitBlock(CopyEnd, /*IsFinished=*/true);
582 return true;
583 }
584 return false;
585}
586
Alexey Bataev38e89532015-04-16 04:54:05 +0000587bool CodeGenFunction::EmitOMPLastprivateClauseInit(
588 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000589 if (!HaveInsertPoint())
590 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000591 bool HasAtLeastOneLastprivate = false;
592 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000593 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000594 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000595 auto IRef = C->varlist_begin();
596 auto IDestRef = C->destination_exprs().begin();
597 for (auto *IInit : C->private_copies()) {
598 // Keep the address of the original variable for future update at the end
599 // of the loop.
600 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
601 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
602 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000603 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000604 DeclRefExpr DRE(
605 const_cast<VarDecl *>(OrigVD),
606 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
607 OrigVD) != nullptr,
608 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
609 return EmitLValue(&DRE).getAddress();
610 });
611 // Check if the variable is also a firstprivate: in this case IInit is
612 // not generated. Initialization of this variable will happen in codegen
613 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000614 if (IInit) {
615 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
616 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000617 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000618 // Emit private VarDecl with copy init.
619 EmitDecl(*VD);
620 return GetAddrOfLocalVar(VD);
621 });
622 assert(IsRegistered &&
623 "lastprivate var already registered as private");
624 (void)IsRegistered;
625 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000626 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000627 ++IRef;
628 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000629 }
630 }
631 return HasAtLeastOneLastprivate;
632}
633
634void CodeGenFunction::EmitOMPLastprivateClauseFinal(
635 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000636 if (!HaveInsertPoint())
637 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000638 // Emit following code:
639 // if (<IsLastIterCond>) {
640 // orig_var1 = private_orig_var1;
641 // ...
642 // orig_varn = private_orig_varn;
643 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000644 llvm::BasicBlock *ThenBB = nullptr;
645 llvm::BasicBlock *DoneBB = nullptr;
646 if (IsLastIterCond) {
647 ThenBB = createBasicBlock(".omp.lastprivate.then");
648 DoneBB = createBasicBlock(".omp.lastprivate.done");
649 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
650 EmitBlock(ThenBB);
651 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000652 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000653 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000654 auto IC = LoopDirective->counters().begin();
655 for (auto F : LoopDirective->finals()) {
656 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
657 LoopCountersAndUpdates[D] = F;
658 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000659 }
660 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000661 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
662 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
663 auto IRef = C->varlist_begin();
664 auto ISrcRef = C->source_exprs().begin();
665 auto IDestRef = C->destination_exprs().begin();
666 for (auto *AssignOp : C->assignment_ops()) {
667 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
668 QualType Type = PrivateVD->getType();
669 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
670 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
671 // If lastprivate variable is a loop control variable for loop-based
672 // directive, update its value before copyin back to original
673 // variable.
674 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
675 EmitIgnoredExpr(UpExpr);
676 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
677 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
678 // Get the address of the original variable.
679 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
680 // Get the address of the private variable.
681 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
682 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
683 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000684 Address(Builder.CreateLoad(PrivateAddr),
685 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000686 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000687 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000688 ++IRef;
689 ++ISrcRef;
690 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000691 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000692 if (auto *PostUpdate = C->getPostUpdateExpr())
693 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000694 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000695 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000696 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000697}
698
Alexey Bataev31300ed2016-02-04 11:27:03 +0000699static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
700 LValue BaseLV, llvm::Value *Addr) {
701 Address Tmp = Address::invalid();
702 Address TopTmp = Address::invalid();
703 Address MostTopTmp = Address::invalid();
704 BaseTy = BaseTy.getNonReferenceType();
705 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
706 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
707 Tmp = CGF.CreateMemTemp(BaseTy);
708 if (TopTmp.isValid())
709 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
710 else
711 MostTopTmp = Tmp;
712 TopTmp = Tmp;
713 BaseTy = BaseTy->getPointeeType();
714 }
715 llvm::Type *Ty = BaseLV.getPointer()->getType();
716 if (Tmp.isValid())
717 Ty = Tmp.getElementType();
718 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
719 if (Tmp.isValid()) {
720 CGF.Builder.CreateStore(Addr, Tmp);
721 return MostTopTmp;
722 }
723 return Address(Addr, BaseLV.getAlignment());
724}
725
726static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
727 LValue BaseLV) {
728 BaseTy = BaseTy.getNonReferenceType();
729 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
730 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
731 if (auto *PtrTy = BaseTy->getAs<PointerType>())
732 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
733 else {
734 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
735 BaseTy->castAs<ReferenceType>());
736 }
737 BaseTy = BaseTy->getPointeeType();
738 }
739 return CGF.MakeAddrLValue(
740 Address(
741 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
742 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
743 BaseLV.getAlignment()),
744 BaseLV.getType(), BaseLV.getAlignmentSource());
745}
746
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000747void CodeGenFunction::EmitOMPReductionClauseInit(
748 const OMPExecutableDirective &D,
749 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000750 if (!HaveInsertPoint())
751 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000752 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000753 auto ILHS = C->lhs_exprs().begin();
754 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000755 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000756 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000757 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000758 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
759 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
760 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
761 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
762 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
763 Base = TempOASE->getBase()->IgnoreParenImpCasts();
764 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
765 Base = TempASE->getBase()->IgnoreParenImpCasts();
766 auto *DE = cast<DeclRefExpr>(Base);
767 auto *OrigVD = cast<VarDecl>(DE->getDecl());
768 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
769 auto OASELValueUB =
770 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
771 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000772 LValue BaseLValue =
773 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
774 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000775 // Store the address of the original variable associated with the LHS
776 // implicit variable.
777 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
778 return OASELValueLB.getAddress();
779 });
780 // Emit reduction copy.
781 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000782 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
783 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000784 // Emit VarDecl with copy init for arrays.
785 // Get the address of the original variable captured in current
786 // captured region.
787 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
788 OASELValueLB.getPointer());
789 Size = Builder.CreateNUWAdd(
790 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
791 CodeGenFunction::OpaqueValueMapping OpaqueMap(
792 *this, cast<OpaqueValueExpr>(
793 getContext()
794 .getAsVariableArrayType(PrivateVD->getType())
795 ->getSizeExpr()),
796 RValue::get(Size));
797 EmitVariablyModifiedType(PrivateVD->getType());
798 auto Emission = EmitAutoVarAlloca(*PrivateVD);
799 auto Addr = Emission.getAllocatedAddress();
800 auto *Init = PrivateVD->getInit();
801 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
802 EmitAutoVarCleanups(Emission);
803 // Emit private VarDecl with reduction init.
804 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
805 OASELValueLB.getPointer());
806 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000807 return castToBase(*this, OrigVD->getType(),
808 OASELValueLB.getType(), OriginalBaseLValue,
809 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000810 });
811 assert(IsRegistered && "private var already registered as private");
812 // Silence the warning about unused variable.
813 (void)IsRegistered;
814 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
815 return GetAddrOfLocalVar(PrivateVD);
816 });
817 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
818 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
819 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
820 Base = TempASE->getBase()->IgnoreParenImpCasts();
821 auto *DE = cast<DeclRefExpr>(Base);
822 auto *OrigVD = cast<VarDecl>(DE->getDecl());
823 auto ASELValue = EmitLValue(ASE);
824 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000825 LValue BaseLValue = loadToBegin(
826 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000827 // Store the address of the original variable associated with the LHS
828 // implicit variable.
829 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
830 return ASELValue.getAddress();
831 });
832 // Emit reduction copy.
833 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000834 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000835 OriginalBaseLValue]() -> Address {
836 // Emit private VarDecl with reduction init.
837 EmitDecl(*PrivateVD);
838 auto Addr = GetAddrOfLocalVar(PrivateVD);
839 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
840 ASELValue.getPointer());
841 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000842 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
843 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000844 });
845 assert(IsRegistered && "private var already registered as private");
846 // Silence the warning about unused variable.
847 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000848 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
849 return Builder.CreateElementBitCast(
850 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
851 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000852 });
853 } else {
854 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000855 QualType Type = PrivateVD->getType();
856 if (getContext().getAsArrayType(Type)) {
857 // Store the address of the original variable associated with the LHS
858 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000859 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
860 CapturedStmtInfo->lookup(OrigVD) != nullptr,
861 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000862 Address OriginalAddr = EmitLValue(&DRE).getAddress();
863 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
864 LHSVD]() -> Address {
865 return Builder.CreateElementBitCast(
866 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
867 "lhs.begin");
868 });
869 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
870 if (Type->isVariablyModifiedType()) {
871 CodeGenFunction::OpaqueValueMapping OpaqueMap(
872 *this, cast<OpaqueValueExpr>(
873 getContext()
874 .getAsVariableArrayType(PrivateVD->getType())
875 ->getSizeExpr()),
876 RValue::get(
877 getTypeSize(OrigVD->getType().getNonReferenceType())));
878 EmitVariablyModifiedType(Type);
879 }
880 auto Emission = EmitAutoVarAlloca(*PrivateVD);
881 auto Addr = Emission.getAllocatedAddress();
882 auto *Init = PrivateVD->getInit();
883 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
884 EmitAutoVarCleanups(Emission);
885 return Emission.getAllocatedAddress();
886 });
887 assert(IsRegistered && "private var already registered as private");
888 // Silence the warning about unused variable.
889 (void)IsRegistered;
890 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
891 return Builder.CreateElementBitCast(
892 GetAddrOfLocalVar(PrivateVD),
893 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
894 });
895 } else {
896 // Store the address of the original variable associated with the LHS
897 // implicit variable.
898 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
899 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
900 CapturedStmtInfo->lookup(OrigVD) != nullptr,
901 IRef->getType(), VK_LValue, IRef->getExprLoc());
902 return EmitLValue(&DRE).getAddress();
903 });
904 // Emit reduction copy.
905 bool IsRegistered =
906 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
907 // Emit private VarDecl with reduction init.
908 EmitDecl(*PrivateVD);
909 return GetAddrOfLocalVar(PrivateVD);
910 });
911 assert(IsRegistered && "private var already registered as private");
912 // Silence the warning about unused variable.
913 (void)IsRegistered;
914 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
915 return GetAddrOfLocalVar(PrivateVD);
916 });
917 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000918 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000919 ++ILHS;
920 ++IRHS;
921 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000922 }
923 }
924}
925
926void CodeGenFunction::EmitOMPReductionClauseFinal(
927 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000928 if (!HaveInsertPoint())
929 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000930 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000931 llvm::SmallVector<const Expr *, 8> LHSExprs;
932 llvm::SmallVector<const Expr *, 8> RHSExprs;
933 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000934 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000935 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000936 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000937 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000938 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
939 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
940 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
941 }
942 if (HasAtLeastOneReduction) {
943 // Emit nowait reduction if nowait clause is present or directive is a
944 // parallel directive (it always has implicit barrier).
945 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000946 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000947 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000948 isOpenMPParallelDirective(D.getDirectiveKind()) ||
949 D.getDirectiveKind() == OMPD_simd,
950 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000951 }
952}
953
Alexey Bataev61205072016-03-02 04:57:40 +0000954static void emitPostUpdateForReductionClause(
955 CodeGenFunction &CGF, const OMPExecutableDirective &D,
956 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
957 if (!CGF.HaveInsertPoint())
958 return;
959 llvm::BasicBlock *DoneBB = nullptr;
960 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
961 if (auto *PostUpdate = C->getPostUpdateExpr()) {
962 if (!DoneBB) {
963 if (auto *Cond = CondGen(CGF)) {
964 // If the first post-update expression is found, emit conditional
965 // block if it was requested.
966 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
967 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
968 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
969 CGF.EmitBlock(ThenBB);
970 }
971 }
972 CGF.EmitIgnoredExpr(PostUpdate);
973 }
974 }
975 if (DoneBB)
976 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
977}
978
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000979static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
980 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000981 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000982 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000983 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000984 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
985 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000986 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
987 emitParallelOrTeamsOutlinedFunction(S,
988 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000989 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000990 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000991 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
992 /*IgnoreResultAssign*/ true);
993 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
994 CGF, NumThreads, NumThreadsClause->getLocStart());
995 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000996 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000997 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000998 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
999 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1000 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001001 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001002 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1003 if (C->getNameModifier() == OMPD_unknown ||
1004 C->getNameModifier() == OMPD_parallel) {
1005 IfCond = C->getCondition();
1006 break;
1007 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001008 }
1009 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001010 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001011}
1012
1013void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001014 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001015 // Emit parallel region as a standalone region.
1016 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1017 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001018 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001019 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1020 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001021 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001022 // propagation master's thread values of threadprivate variables to local
1023 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001024 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1025 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1026 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001027 }
1028 CGF.EmitOMPPrivateClause(S, PrivateScope);
1029 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1030 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001031 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001032 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001033 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001034 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001035 emitPostUpdateForReductionClause(
1036 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001037}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001038
Alexey Bataev0f34da12015-07-02 04:17:07 +00001039void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1040 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001041 RunCleanupsScope BodyScope(*this);
1042 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001043 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001044 EmitIgnoredExpr(I);
1045 }
Alexander Musman3276a272015-03-21 10:12:56 +00001046 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001047 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001048 for (auto U : C->updates()) {
1049 EmitIgnoredExpr(U);
1050 }
1051 }
1052
Alexander Musmana5f070a2014-10-01 06:03:56 +00001053 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001054 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001055 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001056 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001057 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001058 // The end (updates/cleanups).
1059 EmitBlock(Continue.getBlock());
1060 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001061}
1062
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001063void CodeGenFunction::EmitOMPInnerLoop(
1064 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1065 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001066 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1067 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001068 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001069
1070 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001071 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001072 EmitBlock(CondBlock);
1073 LoopStack.push(CondBlock);
1074
1075 // If there are any cleanups between here and the loop-exit scope,
1076 // create a block to stage a loop exit along.
1077 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001078 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001079 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001080
Alexander Musmand196ef22014-10-07 08:57:09 +00001081 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001082
Alexey Bataev2df54a02015-03-12 08:53:29 +00001083 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001084 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001085 if (ExitBlock != LoopExit.getBlock()) {
1086 EmitBlock(ExitBlock);
1087 EmitBranchThroughCleanup(LoopExit);
1088 }
1089
1090 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001091 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001092
1093 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001094 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001095 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1096
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001097 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001098
1099 // Emit "IV = IV + 1" and a back-edge to the condition block.
1100 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001101 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001102 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001103 BreakContinueStack.pop_back();
1104 EmitBranch(CondBlock);
1105 LoopStack.pop();
1106 // Emit the fall-through block.
1107 EmitBlock(LoopExit.getBlock());
1108}
1109
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001110void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001111 if (!HaveInsertPoint())
1112 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001113 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001114 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001115 for (auto Init : C->inits()) {
1116 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001117 auto *OrigVD = cast<VarDecl>(
1118 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1119 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1120 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1121 VD->getInit()->getType(), VK_LValue,
1122 VD->getInit()->getExprLoc());
1123 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1124 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001125 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001126 /*capturedByInit=*/false);
1127 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001128 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001129 // Emit the linear steps for the linear clauses.
1130 // If a step is not constant, it is pre-calculated before the loop.
1131 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1132 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001133 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001134 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001135 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001136 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001137 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001138}
1139
1140static void emitLinearClauseFinal(CodeGenFunction &CGF,
1141 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001142 if (!CGF.HaveInsertPoint())
1143 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001144 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001145 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001146 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001147 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001148 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1149 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001150 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001151 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001152 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001153 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001154 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001155 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001156 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001157 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001158 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001159 }
1160 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001161}
1162
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001163static void emitAlignedClause(CodeGenFunction &CGF,
1164 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001165 if (!CGF.HaveInsertPoint())
1166 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001167 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001168 unsigned ClauseAlignment = 0;
1169 if (auto AlignmentExpr = Clause->getAlignment()) {
1170 auto AlignmentCI =
1171 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1172 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001173 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001174 for (auto E : Clause->varlists()) {
1175 unsigned Alignment = ClauseAlignment;
1176 if (Alignment == 0) {
1177 // OpenMP [2.8.1, Description]
1178 // If no optional parameter is specified, implementation-defined default
1179 // alignments for SIMD instructions on the target platforms are assumed.
1180 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001181 CGF.getContext()
1182 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1183 E->getType()->getPointeeType()))
1184 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001185 }
1186 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1187 "alignment is not power of 2");
1188 if (Alignment != 0) {
1189 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1190 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1191 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001192 }
1193 }
1194}
1195
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001196static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001197 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001198 ArrayRef<Expr *> Counters,
1199 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001200 if (!CGF.HaveInsertPoint())
1201 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001202 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001203 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001204 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1205 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001206 Address Addr = Address::invalid();
1207 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001208 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001209 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001210 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001211 Addr = VarEmission.getAllocatedAddress();
1212 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001213 });
John McCall7f416cc2015-09-08 08:05:57 +00001214 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001215 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001216 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001217}
1218
Alexey Bataev62dbb972015-04-22 11:59:37 +00001219static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1220 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1221 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001222 if (!CGF.HaveInsertPoint())
1223 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001224 {
1225 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001226 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1227 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001228 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001229 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001230 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001231 CGF.EmitIgnoredExpr(I);
1232 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001233 }
1234 // Check that loop is executed at least one time.
1235 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1236}
1237
Alexander Musman3276a272015-03-21 10:12:56 +00001238static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001239emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001240 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001241 if (!CGF.HaveInsertPoint())
1242 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001243 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001244 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001245 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001246 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1247 auto *PrivateVD =
1248 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001249 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001250 // Emit private VarDecl with copy init.
1251 CGF.EmitVarDecl(*PrivateVD);
1252 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001253 });
1254 assert(IsRegistered && "linear var already registered as private");
1255 // Silence the warning about unused variable.
1256 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001257 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001258 }
1259 }
1260}
1261
Alexey Bataev45bfad52015-08-21 12:19:04 +00001262static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001263 const OMPExecutableDirective &D,
1264 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001265 if (!CGF.HaveInsertPoint())
1266 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001267 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001268 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1269 /*ignoreResult=*/true);
1270 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1271 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1272 // In presence of finite 'safelen', it may be unsafe to mark all
1273 // the memory instructions parallel, because loop-carried
1274 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001275 if (!IsMonotonic)
1276 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001277 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001278 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1279 /*ignoreResult=*/true);
1280 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001281 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001282 // In presence of finite 'safelen', it may be unsafe to mark all
1283 // the memory instructions parallel, because loop-carried
1284 // dependences of 'safelen' iterations are possible.
1285 CGF.LoopStack.setParallel(false);
1286 }
1287}
1288
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001289void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1290 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001291 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001292 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001293 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001294 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001295}
1296
1297void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001298 if (!HaveInsertPoint())
1299 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001300 auto IC = D.counters().begin();
1301 for (auto F : D.finals()) {
1302 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001303 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001304 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1305 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1306 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001307 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001308 OMPPrivateScope VarScope(*this);
1309 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001310 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001311 (void)VarScope.Privatize();
1312 EmitIgnoredExpr(F);
1313 }
1314 ++IC;
1315 }
1316 emitLinearClauseFinal(*this, D);
1317}
1318
Alexander Musman515ad8c2014-05-22 08:54:05 +00001319void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001320 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001321 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001322 // for (IV in 0..LastIteration) BODY;
1323 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001324 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001325 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001326
Alexey Bataev62dbb972015-04-22 11:59:37 +00001327 // Emit: if (PreCond) - begin.
1328 // If the condition constant folds and can be elided, avoid emitting the
1329 // whole loop.
1330 bool CondConstant;
1331 llvm::BasicBlock *ContBlock = nullptr;
1332 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1333 if (!CondConstant)
1334 return;
1335 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001336 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1337 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001338 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1339 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001340 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001341 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001342 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001343
1344 // Emit the loop iteration variable.
1345 const Expr *IVExpr = S.getIterationVariable();
1346 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1347 CGF.EmitVarDecl(*IVDecl);
1348 CGF.EmitIgnoredExpr(S.getInit());
1349
1350 // Emit the iterations count variable.
1351 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001352 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001353 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1354 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1355 // Emit calculation of the iterations count.
1356 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001357 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001358
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001359 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001360
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001361 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001362 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001363 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001364 {
1365 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001366 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1367 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001369 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001370 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001371 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001372 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001373 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1374 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001375 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001376 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001377 CGF.EmitStopPoint(&S);
1378 },
1379 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001380 // Emit final copy of the lastprivate variables at the end of loops.
1381 if (HasLastprivateClause) {
1382 CGF.EmitOMPLastprivateClauseFinal(S);
1383 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001384 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001385 emitPostUpdateForReductionClause(
1386 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001387 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001388 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001389 // Emit: if (PreCond) - end.
1390 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001391 CGF.EmitBranch(ContBlock);
1392 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001393 }
1394 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001395 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001396}
1397
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001398void CodeGenFunction::EmitOMPForOuterLoop(
1399 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1400 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1401 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001402 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001403
1404 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001405 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001406
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001407 assert((Ordered ||
1408 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001409 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001410
1411 // Emit outer loop.
1412 //
1413 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001414 // When schedule(dynamic,chunk_size) is specified, the iterations are
1415 // distributed to threads in the team in chunks as the threads request them.
1416 // Each thread executes a chunk of iterations, then requests another chunk,
1417 // until no chunks remain to be distributed. Each chunk contains chunk_size
1418 // iterations, except for the last chunk to be distributed, which may have
1419 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1420 //
1421 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1422 // to threads in the team in chunks as the executing threads request them.
1423 // Each thread executes a chunk of iterations, then requests another chunk,
1424 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1425 // each chunk is proportional to the number of unassigned iterations divided
1426 // by the number of threads in the team, decreasing to 1. For a chunk_size
1427 // with value k (greater than 1), the size of each chunk is determined in the
1428 // same way, with the restriction that the chunks do not contain fewer than k
1429 // iterations (except for the last chunk to be assigned, which may have fewer
1430 // than k iterations).
1431 //
1432 // When schedule(auto) is specified, the decision regarding scheduling is
1433 // delegated to the compiler and/or runtime system. The programmer gives the
1434 // implementation the freedom to choose any possible mapping of iterations to
1435 // threads in the team.
1436 //
1437 // When schedule(runtime) is specified, the decision regarding scheduling is
1438 // deferred until run time, and the schedule and chunk size are taken from the
1439 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1440 // implementation defined
1441 //
1442 // while(__kmpc_dispatch_next(&LB, &UB)) {
1443 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001444 // while (idx <= UB) { BODY; ++idx;
1445 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1446 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001447 // }
1448 //
1449 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001450 // When schedule(static, chunk_size) is specified, iterations are divided into
1451 // chunks of size chunk_size, and the chunks are assigned to the threads in
1452 // the team in a round-robin fashion in the order of the thread number.
1453 //
1454 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1455 // while (idx <= UB) { BODY; ++idx; } // inner loop
1456 // LB = LB + ST;
1457 // UB = UB + ST;
1458 // }
1459 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001460
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001461 const Expr *IVExpr = S.getIterationVariable();
1462 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1463 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1464
John McCall7f416cc2015-09-08 08:05:57 +00001465 if (DynamicOrOrdered) {
1466 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1467 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1468 IVSize, IVSigned, Ordered, UBVal, Chunk);
1469 } else {
1470 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1471 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1472 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001473
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001474 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1475
1476 // Start the loop with a block that tests the condition.
1477 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1478 EmitBlock(CondBlock);
1479 LoopStack.push(CondBlock);
1480
1481 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001482 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001483 // UB = min(UB, GlobalUB)
1484 EmitIgnoredExpr(S.getEnsureUpperBound());
1485 // IV = LB
1486 EmitIgnoredExpr(S.getInit());
1487 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001488 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001489 } else {
1490 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1491 IL, LB, UB, ST);
1492 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001493
1494 // If there are any cleanups between here and the loop-exit scope,
1495 // create a block to stage a loop exit along.
1496 auto ExitBlock = LoopExit.getBlock();
1497 if (LoopScope.requiresCleanups())
1498 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1499
1500 auto LoopBody = createBasicBlock("omp.dispatch.body");
1501 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1502 if (ExitBlock != LoopExit.getBlock()) {
1503 EmitBlock(ExitBlock);
1504 EmitBranchThroughCleanup(LoopExit);
1505 }
1506 EmitBlock(LoopBody);
1507
Alexander Musman92bdaab2015-03-12 13:37:50 +00001508 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1509 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001510 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001511 EmitIgnoredExpr(S.getInit());
1512
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001513 // Create a block for the increment.
1514 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1515 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1516
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001517 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1518 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001519 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1520 LoopStack.setParallel(!IsMonotonic);
1521 else
1522 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001523
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001524 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001525 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1526 [&S, LoopExit](CodeGenFunction &CGF) {
1527 CGF.EmitOMPLoopBody(S, LoopExit);
1528 CGF.EmitStopPoint(&S);
1529 },
1530 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1531 if (Ordered) {
1532 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1533 CGF, Loc, IVSize, IVSigned);
1534 }
1535 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001536
1537 EmitBlock(Continue.getBlock());
1538 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001539 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001540 // Emit "LB = LB + Stride", "UB = UB + Stride".
1541 EmitIgnoredExpr(S.getNextLowerBound());
1542 EmitIgnoredExpr(S.getNextUpperBound());
1543 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001544
1545 EmitBranch(CondBlock);
1546 LoopStack.pop();
1547 // Emit the fall-through block.
1548 EmitBlock(LoopExit.getBlock());
1549
1550 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001551 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001552 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001553}
1554
Alexander Musmanc6388682014-12-15 07:07:06 +00001555/// \brief Emit a helper variable and return corresponding lvalue.
1556static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1557 const DeclRefExpr *Helper) {
1558 auto VDecl = cast<VarDecl>(Helper->getDecl());
1559 CGF.EmitVarDecl(*VDecl);
1560 return CGF.EmitLValue(Helper);
1561}
1562
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001563namespace {
1564 struct ScheduleKindModifiersTy {
1565 OpenMPScheduleClauseKind Kind;
1566 OpenMPScheduleClauseModifier M1;
1567 OpenMPScheduleClauseModifier M2;
1568 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1569 OpenMPScheduleClauseModifier M1,
1570 OpenMPScheduleClauseModifier M2)
1571 : Kind(Kind), M1(M1), M2(M2) {}
1572 };
1573} // namespace
1574
Alexey Bataev38e89532015-04-16 04:54:05 +00001575bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001576 // Emit the loop iteration variable.
1577 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1578 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1579 EmitVarDecl(*IVDecl);
1580
1581 // Emit the iterations count variable.
1582 // If it is not a variable, Sema decided to calculate iterations count on each
1583 // iteration (e.g., it is foldable into a constant).
1584 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1585 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1586 // Emit calculation of the iterations count.
1587 EmitIgnoredExpr(S.getCalcLastIteration());
1588 }
1589
1590 auto &RT = CGM.getOpenMPRuntime();
1591
Alexey Bataev38e89532015-04-16 04:54:05 +00001592 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001593 // Check pre-condition.
1594 {
1595 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001596 // If the condition constant folds and can be elided, avoid emitting the
1597 // whole loop.
1598 bool CondConstant;
1599 llvm::BasicBlock *ContBlock = nullptr;
1600 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1601 if (!CondConstant)
1602 return false;
1603 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001604 auto *ThenBlock = createBasicBlock("omp.precond.then");
1605 ContBlock = createBasicBlock("omp.precond.end");
1606 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001607 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001608 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001609 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001610 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001611
1612 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001613 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001614 // Emit 'then' code.
1615 {
1616 // Emit helper vars inits.
1617 LValue LB =
1618 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1619 LValue UB =
1620 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1621 LValue ST =
1622 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1623 LValue IL =
1624 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1625
1626 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001627 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1628 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001629 // initialization of firstprivate variables and post-update of
1630 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001631 CGM.getOpenMPRuntime().emitBarrierCall(
1632 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1633 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001634 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001635 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001636 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001637 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001638 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1639 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001640 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001641 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001642
1643 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001644 llvm::Value *Chunk = nullptr;
1645 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1646 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1647 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1648 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1649 ScheduleKind = C->getScheduleKind();
1650 M1 = C->getFirstScheduleModifier();
1651 M2 = C->getSecondScheduleModifier();
1652 if (const auto *Ch = C->getChunkSize()) {
1653 Chunk = EmitScalarExpr(Ch);
1654 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1655 S.getIterationVariable()->getType(),
1656 S.getLocStart());
1657 }
1658 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001659 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1660 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001661 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001662 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1663 // If the static schedule kind is specified or if the ordered clause is
1664 // specified, and if no monotonic modifier is specified, the effect will
1665 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001666 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001667 /* Chunked */ Chunk != nullptr) &&
1668 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001669 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1670 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001671 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1672 // When no chunk_size is specified, the iteration space is divided into
1673 // chunks that are approximately equal in size, and at most one chunk is
1674 // distributed to each thread. Note that the size of the chunks is
1675 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001676 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1677 IVSize, IVSigned, Ordered,
1678 IL.getAddress(), LB.getAddress(),
1679 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001680 auto LoopExit =
1681 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001682 // UB = min(UB, GlobalUB);
1683 EmitIgnoredExpr(S.getEnsureUpperBound());
1684 // IV = LB;
1685 EmitIgnoredExpr(S.getInit());
1686 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001687 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1688 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001689 [&S, LoopExit](CodeGenFunction &CGF) {
1690 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001691 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001692 },
1693 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001694 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001695 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001696 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001697 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001698 const bool IsMonotonic = Ordered ||
1699 ScheduleKind == OMPC_SCHEDULE_static ||
1700 ScheduleKind == OMPC_SCHEDULE_unknown ||
1701 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1702 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001703 // Emit the outer loop, which requests its work chunk [LB..UB] from
1704 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001705 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001706 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1707 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001708 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001709 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001710 // Emit post-update of the reduction variables if IsLastIter != 0.
1711 emitPostUpdateForReductionClause(
1712 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1713 return CGF.Builder.CreateIsNotNull(
1714 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1715 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001716 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1717 if (HasLastprivateClause)
1718 EmitOMPLastprivateClauseFinal(
1719 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001720 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001721 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1722 EmitOMPSimdFinal(S);
1723 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001724 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001725 if (ContBlock) {
1726 EmitBranch(ContBlock);
1727 EmitBlock(ContBlock, true);
1728 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001729 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001730 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001731}
1732
1733void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001734 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001735 {
1736 OMPLexicalScope Scope(*this, S);
1737 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1738 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1739 };
1740 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1741 S.hasCancel());
1742 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001743
1744 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001745 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001746 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1747 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001748}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001749
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001750void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001751 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001752 {
1753 OMPLexicalScope Scope(*this, S);
1754 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1755 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1756 };
1757 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1758 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001759
1760 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001761 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001762 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1763 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001764}
1765
Alexey Bataev2df54a02015-03-12 08:53:29 +00001766static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1767 const Twine &Name,
1768 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001769 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001770 if (Init)
1771 CGF.EmitScalarInit(Init, LVal);
1772 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001773}
1774
Alexey Bataev3392d762016-02-16 11:18:12 +00001775void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001776 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1777 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001778 bool HasLastprivates = false;
1779 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1780 auto &C = CGF.CGM.getContext();
1781 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1782 // Emit helper vars inits.
1783 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1784 CGF.Builder.getInt32(0));
1785 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1786 : CGF.Builder.getInt32(0);
1787 LValue UB =
1788 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1789 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1790 CGF.Builder.getInt32(1));
1791 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1792 CGF.Builder.getInt32(0));
1793 // Loop counter.
1794 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1795 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1796 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1797 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1798 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1799 // Generate condition for loop.
1800 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1801 OK_Ordinary, S.getLocStart(),
1802 /*fpContractable=*/false);
1803 // Increment for loop counter.
1804 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1805 S.getLocStart());
1806 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1807 // Iterate through all sections and emit a switch construct:
1808 // switch (IV) {
1809 // case 0:
1810 // <SectionStmt[0]>;
1811 // break;
1812 // ...
1813 // case <NumSection> - 1:
1814 // <SectionStmt[<NumSection> - 1]>;
1815 // break;
1816 // }
1817 // .omp.sections.exit:
1818 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1819 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1820 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1821 CS == nullptr ? 1 : CS->size());
1822 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001823 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001824 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001825 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1826 CGF.EmitBlock(CaseBB);
1827 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001828 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001829 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001830 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001831 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001832 } else {
1833 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1834 CGF.EmitBlock(CaseBB);
1835 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1836 CGF.EmitStmt(Stmt);
1837 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001838 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001839 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001840 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001841
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001842 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1843 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001844 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001845 // initialization of firstprivate variables and post-update of lastprivate
1846 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001847 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1848 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1849 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001850 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001851 CGF.EmitOMPPrivateClause(S, LoopScope);
1852 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1853 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1854 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001855
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001856 // Emit static non-chunked loop.
1857 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1858 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1859 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1860 UB.getAddress(), ST.getAddress());
1861 // UB = min(UB, GlobalUB);
1862 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1863 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1864 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1865 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1866 // IV = LB;
1867 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1868 // while (idx <= UB) { BODY; ++idx; }
1869 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1870 [](CodeGenFunction &) {});
1871 // Tell the runtime we are done.
1872 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1873 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001874 // Emit post-update of the reduction variables if IsLastIter != 0.
1875 emitPostUpdateForReductionClause(
1876 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1877 return CGF.Builder.CreateIsNotNull(
1878 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1879 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001880
1881 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1882 if (HasLastprivates)
1883 CGF.EmitOMPLastprivateClauseFinal(
1884 S, CGF.Builder.CreateIsNotNull(
1885 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001886 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001887
1888 bool HasCancel = false;
1889 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1890 HasCancel = OSD->hasCancel();
1891 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1892 HasCancel = OPSD->hasCancel();
1893 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1894 HasCancel);
1895 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1896 // clause. Otherwise the barrier will be generated by the codegen for the
1897 // directive.
1898 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001899 // Emit implicit barrier to synchronize threads and avoid data races on
1900 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001901 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1902 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001903 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001904}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001905
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001906void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001907 {
1908 OMPLexicalScope Scope(*this, S);
1909 EmitSections(S);
1910 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001911 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001912 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001913 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1914 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001915 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001916}
1917
1918void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &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 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001923 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1924 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001925}
1926
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001927void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001928 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001929 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001930 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001931 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001932 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001933 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001934 // Build a list of copyprivate variables along with helper expressions
1935 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001936 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001937 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001938 DestExprs.append(C->destination_exprs().begin(),
1939 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001940 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001941 AssignmentOps.append(C->assignment_ops().begin(),
1942 C->assignment_ops().end());
1943 }
Alexey Bataev3392d762016-02-16 11:18:12 +00001944 {
1945 OMPLexicalScope Scope(*this, S);
1946 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00001947 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001948 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00001949 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00001950 CGF.EmitOMPPrivateClause(S, SingleScope);
1951 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00001952 CGF.EmitStmt(
1953 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1954 };
1955 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1956 CopyprivateVars, DestExprs,
1957 SrcExprs, AssignmentOps);
1958 }
1959 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1960 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00001961 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00001962 CGM.getOpenMPRuntime().emitBarrierCall(
1963 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001964 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001965 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001966}
1967
Alexey Bataev8d690652014-12-04 07:23:53 +00001968void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001969 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001970 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1971 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001972 };
1973 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001974}
1975
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001976void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001977 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001978 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1979 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001980 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001981 Expr *Hint = nullptr;
1982 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1983 Hint = HintClause->getHint();
1984 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1985 S.getDirectiveName().getAsString(),
1986 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001987}
1988
Alexey Bataev671605e2015-04-13 05:28:11 +00001989void CodeGenFunction::EmitOMPParallelForDirective(
1990 const OMPParallelForDirective &S) {
1991 // Emit directive as a combined directive that consists of two implicit
1992 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001993 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001994 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1995 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001996 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001997 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001998}
1999
Alexander Musmane4e893b2014-09-23 09:33:00 +00002000void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002001 const OMPParallelForSimdDirective &S) {
2002 // Emit directive as a combined directive that consists of two implicit
2003 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002004 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002005 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2006 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002007 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002008 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002009}
2010
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002011void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002012 const OMPParallelSectionsDirective &S) {
2013 // Emit directive as a combined directive that consists of two implicit
2014 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002015 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00002016 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002017 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002018}
2019
Alexey Bataev62b63b12015-03-10 07:28:44 +00002020void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2021 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00002022 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002023 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2024 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2025 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002026 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002027 // The first function argument for tasks is a thread id, the second one is a
2028 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002029 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2030 // Get list of private variables.
2031 llvm::SmallVector<const Expr *, 8> PrivateVars;
2032 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002033 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002034 auto IRef = C->varlist_begin();
2035 for (auto *IInit : C->private_copies()) {
2036 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2037 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2038 PrivateVars.push_back(*IRef);
2039 PrivateCopies.push_back(IInit);
2040 }
2041 ++IRef;
2042 }
2043 }
2044 EmittedAsPrivate.clear();
2045 // Get list of firstprivate variables.
2046 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2047 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2048 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002049 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002050 auto IRef = C->varlist_begin();
2051 auto IElemInitRef = C->inits().begin();
2052 for (auto *IInit : C->private_copies()) {
2053 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2054 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2055 FirstprivateVars.push_back(*IRef);
2056 FirstprivateCopies.push_back(IInit);
2057 FirstprivateInits.push_back(*IElemInitRef);
2058 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002059 ++IRef;
2060 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002061 }
2062 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002063 // Build list of dependences.
2064 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2065 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002066 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002067 for (auto *IRef : C->varlists()) {
2068 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2069 }
2070 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002071 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2072 CodeGenFunction &CGF) {
2073 // Set proper addresses for generated private copies.
2074 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2075 OMPPrivateScope Scope(CGF);
2076 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002077 auto *CopyFn = CGF.Builder.CreateLoad(
2078 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2079 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2080 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002081 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002082 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002083 PrivatePtrs;
2084 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2085 CallArgs.push_back(PrivatesPtr);
2086 for (auto *E : PrivateVars) {
2087 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002088 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002089 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2090 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002091 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002092 }
2093 for (auto *E : FirstprivateVars) {
2094 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002095 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002096 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2097 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002098 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002099 }
2100 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2101 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002102 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2103 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002104 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2105 }
2106 }
2107 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002108 if (*PartId) {
2109 // TODO: emit code for untied tasks.
2110 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002111 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002112 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002113 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2114 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002115 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002116 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002117 // Check if the task is final
2118 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002119 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002120 // If the condition constant folds and can be elided, try to avoid emitting
2121 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002122 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002123 bool CondConstant;
2124 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2125 Final.setInt(CondConstant);
2126 else
2127 Final.setPointer(EvaluateExprAsBool(Cond));
2128 } else {
2129 // By default the task is not final.
2130 Final.setInt(/*IntVal=*/false);
2131 }
2132 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002133 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002134 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2135 if (C->getNameModifier() == OMPD_unknown ||
2136 C->getNameModifier() == OMPD_task) {
2137 IfCond = C->getCondition();
2138 break;
2139 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002140 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002141 CGM.getOpenMPRuntime().emitTaskCall(
2142 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002143 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002144 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002145}
2146
Alexey Bataev9f797f32015-02-05 05:57:51 +00002147void CodeGenFunction::EmitOMPTaskyieldDirective(
2148 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002149 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002150}
2151
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002152void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002153 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002154}
2155
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002156void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2157 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002158}
2159
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002160void CodeGenFunction::EmitOMPTaskgroupDirective(
2161 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002162 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002163 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2164 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002165 };
2166 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2167}
2168
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002169void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002170 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002171 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002172 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2173 FlushClause->varlist_end());
2174 }
2175 return llvm::None;
2176 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002177}
2178
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002179void CodeGenFunction::EmitOMPDistributeDirective(
2180 const OMPDistributeDirective &S) {
2181 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2182}
2183
Alexey Bataev5f600d62015-09-29 03:48:57 +00002184static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2185 const CapturedStmt *S) {
2186 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2187 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2188 CGF.CapturedStmtInfo = &CapStmtInfo;
2189 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2190 Fn->addFnAttr(llvm::Attribute::NoInline);
2191 return Fn;
2192}
2193
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002194void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002195 if (!S.getAssociatedStmt())
2196 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002197 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002198 auto *C = S.getSingleClause<OMPSIMDClause>();
2199 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2200 if (C) {
2201 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2202 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2203 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2204 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2205 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2206 } else {
2207 CGF.EmitStmt(
2208 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2209 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002210 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002211 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002212}
2213
Alexey Bataevb57056f2015-01-22 06:17:56 +00002214static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002215 QualType SrcType, QualType DestType,
2216 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002217 assert(CGF.hasScalarEvaluationKind(DestType) &&
2218 "DestType must have scalar evaluation kind.");
2219 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2220 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002221 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2222 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002223 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002224 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002225}
2226
2227static CodeGenFunction::ComplexPairTy
2228convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002229 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002230 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2231 "DestType must have complex evaluation kind.");
2232 CodeGenFunction::ComplexPairTy ComplexVal;
2233 if (Val.isScalar()) {
2234 // Convert the input element to the element type of the complex.
2235 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002236 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2237 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002238 ComplexVal = CodeGenFunction::ComplexPairTy(
2239 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2240 } else {
2241 assert(Val.isComplex() && "Must be a scalar or complex.");
2242 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2243 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2244 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002245 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002246 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002247 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002248 }
2249 return ComplexVal;
2250}
2251
Alexey Bataev5e018f92015-04-23 06:35:10 +00002252static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2253 LValue LVal, RValue RVal) {
2254 if (LVal.isGlobalReg()) {
2255 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2256 } else {
2257 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2258 : llvm::Monotonic,
2259 LVal.isVolatile(), /*IsInit=*/false);
2260 }
2261}
2262
Alexey Bataev8524d152016-01-21 12:35:58 +00002263void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2264 QualType RValTy, SourceLocation Loc) {
2265 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002266 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002267 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2268 *this, RVal, RValTy, LVal.getType(), Loc)),
2269 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002270 break;
2271 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002272 EmitStoreOfComplex(
2273 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002274 /*isInit=*/false);
2275 break;
2276 case TEK_Aggregate:
2277 llvm_unreachable("Must be a scalar or complex.");
2278 }
2279}
2280
Alexey Bataevb57056f2015-01-22 06:17:56 +00002281static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2282 const Expr *X, const Expr *V,
2283 SourceLocation Loc) {
2284 // v = x;
2285 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2286 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2287 LValue XLValue = CGF.EmitLValue(X);
2288 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002289 RValue Res = XLValue.isGlobalReg()
2290 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2291 : CGF.EmitAtomicLoad(XLValue, Loc,
2292 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002293 : llvm::Monotonic,
2294 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002295 // OpenMP, 2.12.6, atomic Construct
2296 // Any atomic construct with a seq_cst clause forces the atomically
2297 // performed operation to include an implicit flush operation without a
2298 // list.
2299 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002300 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002301 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002302}
2303
Alexey Bataevb8329262015-02-27 06:33:30 +00002304static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2305 const Expr *X, const Expr *E,
2306 SourceLocation Loc) {
2307 // x = expr;
2308 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002309 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002310 // OpenMP, 2.12.6, atomic Construct
2311 // Any atomic construct with a seq_cst clause forces the atomically
2312 // performed operation to include an implicit flush operation without a
2313 // list.
2314 if (IsSeqCst)
2315 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2316}
2317
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002318static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2319 RValue Update,
2320 BinaryOperatorKind BO,
2321 llvm::AtomicOrdering AO,
2322 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002323 auto &Context = CGF.CGM.getContext();
2324 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002325 // expression is simple and atomic is allowed for the given type for the
2326 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002327 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002328 !Update.getScalarVal()->getType()->isIntegerTy() ||
2329 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2330 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002331 X.getAddress().getElementType())) ||
2332 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002333 !Context.getTargetInfo().hasBuiltinAtomic(
2334 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002335 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002336
2337 llvm::AtomicRMWInst::BinOp RMWOp;
2338 switch (BO) {
2339 case BO_Add:
2340 RMWOp = llvm::AtomicRMWInst::Add;
2341 break;
2342 case BO_Sub:
2343 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002344 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002345 RMWOp = llvm::AtomicRMWInst::Sub;
2346 break;
2347 case BO_And:
2348 RMWOp = llvm::AtomicRMWInst::And;
2349 break;
2350 case BO_Or:
2351 RMWOp = llvm::AtomicRMWInst::Or;
2352 break;
2353 case BO_Xor:
2354 RMWOp = llvm::AtomicRMWInst::Xor;
2355 break;
2356 case BO_LT:
2357 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2358 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2359 : llvm::AtomicRMWInst::Max)
2360 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2361 : llvm::AtomicRMWInst::UMax);
2362 break;
2363 case BO_GT:
2364 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2365 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2366 : llvm::AtomicRMWInst::Min)
2367 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2368 : llvm::AtomicRMWInst::UMin);
2369 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002370 case BO_Assign:
2371 RMWOp = llvm::AtomicRMWInst::Xchg;
2372 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002373 case BO_Mul:
2374 case BO_Div:
2375 case BO_Rem:
2376 case BO_Shl:
2377 case BO_Shr:
2378 case BO_LAnd:
2379 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002380 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002381 case BO_PtrMemD:
2382 case BO_PtrMemI:
2383 case BO_LE:
2384 case BO_GE:
2385 case BO_EQ:
2386 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002387 case BO_AddAssign:
2388 case BO_SubAssign:
2389 case BO_AndAssign:
2390 case BO_OrAssign:
2391 case BO_XorAssign:
2392 case BO_MulAssign:
2393 case BO_DivAssign:
2394 case BO_RemAssign:
2395 case BO_ShlAssign:
2396 case BO_ShrAssign:
2397 case BO_Comma:
2398 llvm_unreachable("Unsupported atomic update operation");
2399 }
2400 auto *UpdateVal = Update.getScalarVal();
2401 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2402 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002403 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002404 X.getType()->hasSignedIntegerRepresentation());
2405 }
John McCall7f416cc2015-09-08 08:05:57 +00002406 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002407 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002408}
2409
Alexey Bataev5e018f92015-04-23 06:35:10 +00002410std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002411 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2412 llvm::AtomicOrdering AO, SourceLocation Loc,
2413 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2414 // Update expressions are allowed to have the following forms:
2415 // x binop= expr; -> xrval + expr;
2416 // x++, ++x -> xrval + 1;
2417 // x--, --x -> xrval - 1;
2418 // x = x binop expr; -> xrval binop expr
2419 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002420 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2421 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002422 if (X.isGlobalReg()) {
2423 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2424 // 'xrval'.
2425 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2426 } else {
2427 // Perform compare-and-swap procedure.
2428 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002429 }
2430 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002431 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002432}
2433
2434static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2435 const Expr *X, const Expr *E,
2436 const Expr *UE, bool IsXLHSInRHSPart,
2437 SourceLocation Loc) {
2438 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2439 "Update expr in 'atomic update' must be a binary operator.");
2440 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2441 // Update expressions are allowed to have the following forms:
2442 // x binop= expr; -> xrval + expr;
2443 // x++, ++x -> xrval + 1;
2444 // x--, --x -> xrval - 1;
2445 // x = x binop expr; -> xrval binop expr
2446 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002447 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002448 LValue XLValue = CGF.EmitLValue(X);
2449 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002450 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002451 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2452 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2453 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2454 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2455 auto Gen =
2456 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2457 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2458 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2459 return CGF.EmitAnyExpr(UE);
2460 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002461 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2462 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2463 // OpenMP, 2.12.6, atomic Construct
2464 // Any atomic construct with a seq_cst clause forces the atomically
2465 // performed operation to include an implicit flush operation without a
2466 // list.
2467 if (IsSeqCst)
2468 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2469}
2470
2471static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002472 QualType SourceType, QualType ResType,
2473 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002474 switch (CGF.getEvaluationKind(ResType)) {
2475 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002476 return RValue::get(
2477 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002478 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002479 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002480 return RValue::getComplex(Res.first, Res.second);
2481 }
2482 case TEK_Aggregate:
2483 break;
2484 }
2485 llvm_unreachable("Must be a scalar or complex.");
2486}
2487
2488static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2489 bool IsPostfixUpdate, const Expr *V,
2490 const Expr *X, const Expr *E,
2491 const Expr *UE, bool IsXLHSInRHSPart,
2492 SourceLocation Loc) {
2493 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2494 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2495 RValue NewVVal;
2496 LValue VLValue = CGF.EmitLValue(V);
2497 LValue XLValue = CGF.EmitLValue(X);
2498 RValue ExprRValue = CGF.EmitAnyExpr(E);
2499 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2500 QualType NewVValType;
2501 if (UE) {
2502 // 'x' is updated with some additional value.
2503 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2504 "Update expr in 'atomic capture' must be a binary operator.");
2505 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2506 // Update expressions are allowed to have the following forms:
2507 // x binop= expr; -> xrval + expr;
2508 // x++, ++x -> xrval + 1;
2509 // x--, --x -> xrval - 1;
2510 // x = x binop expr; -> xrval binop expr
2511 // x = expr Op x; - > expr binop xrval;
2512 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2513 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2514 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2515 NewVValType = XRValExpr->getType();
2516 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2517 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2518 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2519 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2520 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2521 RValue Res = CGF.EmitAnyExpr(UE);
2522 NewVVal = IsPostfixUpdate ? XRValue : Res;
2523 return Res;
2524 };
2525 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2526 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2527 if (Res.first) {
2528 // 'atomicrmw' instruction was generated.
2529 if (IsPostfixUpdate) {
2530 // Use old value from 'atomicrmw'.
2531 NewVVal = Res.second;
2532 } else {
2533 // 'atomicrmw' does not provide new value, so evaluate it using old
2534 // value of 'x'.
2535 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2536 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2537 NewVVal = CGF.EmitAnyExpr(UE);
2538 }
2539 }
2540 } else {
2541 // 'x' is simply rewritten with some 'expr'.
2542 NewVValType = X->getType().getNonReferenceType();
2543 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002544 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002545 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2546 NewVVal = XRValue;
2547 return ExprRValue;
2548 };
2549 // Try to perform atomicrmw xchg, otherwise simple exchange.
2550 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2551 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2552 Loc, Gen);
2553 if (Res.first) {
2554 // 'atomicrmw' instruction was generated.
2555 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2556 }
2557 }
2558 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002559 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002560 // OpenMP, 2.12.6, atomic Construct
2561 // Any atomic construct with a seq_cst clause forces the atomically
2562 // performed operation to include an implicit flush operation without a
2563 // list.
2564 if (IsSeqCst)
2565 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2566}
2567
Alexey Bataevb57056f2015-01-22 06:17:56 +00002568static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002569 bool IsSeqCst, bool IsPostfixUpdate,
2570 const Expr *X, const Expr *V, const Expr *E,
2571 const Expr *UE, bool IsXLHSInRHSPart,
2572 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002573 switch (Kind) {
2574 case OMPC_read:
2575 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2576 break;
2577 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002578 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2579 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002580 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002581 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002582 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2583 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002584 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002585 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2586 IsXLHSInRHSPart, Loc);
2587 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002588 case OMPC_if:
2589 case OMPC_final:
2590 case OMPC_num_threads:
2591 case OMPC_private:
2592 case OMPC_firstprivate:
2593 case OMPC_lastprivate:
2594 case OMPC_reduction:
2595 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002596 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002597 case OMPC_collapse:
2598 case OMPC_default:
2599 case OMPC_seq_cst:
2600 case OMPC_shared:
2601 case OMPC_linear:
2602 case OMPC_aligned:
2603 case OMPC_copyin:
2604 case OMPC_copyprivate:
2605 case OMPC_flush:
2606 case OMPC_proc_bind:
2607 case OMPC_schedule:
2608 case OMPC_ordered:
2609 case OMPC_nowait:
2610 case OMPC_untied:
2611 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002612 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002613 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002614 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002615 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002616 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002617 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002618 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002619 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002620 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002621 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002622 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002623 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002624 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002625 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002626 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002627 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2628 }
2629}
2630
2631void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002632 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002633 OpenMPClauseKind Kind = OMPC_unknown;
2634 for (auto *C : S.clauses()) {
2635 // Find first clause (skip seq_cst clause, if it is first).
2636 if (C->getClauseKind() != OMPC_seq_cst) {
2637 Kind = C->getClauseKind();
2638 break;
2639 }
2640 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002641
2642 const auto *CS =
2643 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002644 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002645 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002646 }
2647 // Processing for statements under 'atomic capture'.
2648 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2649 for (const auto *C : Compound->body()) {
2650 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2651 enterFullExpression(EWC);
2652 }
2653 }
2654 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002655
Alexey Bataev3392d762016-02-16 11:18:12 +00002656 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002657 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2658 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002659 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2660 S.getV(), S.getExpr(), S.getUpdateExpr(),
2661 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002662 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002663 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002664}
2665
Samuel Antaobed3c462015-10-02 16:14:20 +00002666void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002667 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002668 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2669
2670 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002671 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002672
Samuel Antaoee8fb302016-01-06 13:42:12 +00002673 llvm::Function *Fn = nullptr;
2674 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002675
2676 // Check if we have any if clause associated with the directive.
2677 const Expr *IfCond = nullptr;
2678
2679 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2680 IfCond = C->getCondition();
2681 }
2682
2683 // Check if we have any device clause associated with the directive.
2684 const Expr *Device = nullptr;
2685 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2686 Device = C->getDevice();
2687 }
2688
Samuel Antaoee8fb302016-01-06 13:42:12 +00002689 // Check if we have an if clause whose conditional always evaluates to false
2690 // or if we do not have any targets specified. If so the target region is not
2691 // an offload entry point.
2692 bool IsOffloadEntry = true;
2693 if (IfCond) {
2694 bool Val;
2695 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2696 IsOffloadEntry = false;
2697 }
2698 if (CGM.getLangOpts().OMPTargetTriples.empty())
2699 IsOffloadEntry = false;
2700
2701 assert(CurFuncDecl && "No parent declaration for target region!");
2702 StringRef ParentName;
2703 // In case we have Ctors/Dtors we use the complete type variant to produce
2704 // the mangling of the device outlined kernel.
2705 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2706 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2707 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2708 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2709 else
2710 ParentName =
2711 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2712
2713 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2714 IsOffloadEntry);
2715
2716 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002717 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002718}
2719
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002720static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
2721 const OMPExecutableDirective &S,
2722 OpenMPDirectiveKind InnermostKind,
2723 const RegionCodeGenTy &CodeGen) {
2724 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2725 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2726 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2727 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
2728 emitParallelOrTeamsOutlinedFunction(S,
2729 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00002730
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002731 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
2732 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
2733 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
2734 if (NT || TL) {
2735 llvm::Value *NumTeamsVal = (NT) ? CGF.Builder.CreateIntCast(
2736 CGF.EmitScalarExpr(NT->getNumTeams()), CGF.CGM.Int32Ty,
2737 /* isSigned = */ true) :
2738 CGF.Builder.getInt32(0);
2739
2740 llvm::Value *ThreadLimitVal = (TL) ? CGF.Builder.CreateIntCast(
2741 CGF.EmitScalarExpr(TL->getThreadLimit()), CGF.CGM.Int32Ty,
2742 /* isSigned = */ true) :
2743 CGF.Builder.getInt32(0);
2744
2745 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeamsVal,
2746 ThreadLimitVal, S.getLocStart());
2747 }
2748
2749 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
2750 CapturedVars);
2751}
2752
2753void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
2754 LexicalScope Scope(*this, S.getSourceRange());
2755 // Emit parallel region as a standalone region.
2756 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2757 OMPPrivateScope PrivateScope(CGF);
2758 (void)PrivateScope.Privatize();
2759 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2760 };
2761 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002762}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002763
2764void CodeGenFunction::EmitOMPCancellationPointDirective(
2765 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002766 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2767 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002768}
2769
Alexey Bataev80909872015-07-02 11:25:17 +00002770void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002771 const Expr *IfCond = nullptr;
2772 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2773 if (C->getNameModifier() == OMPD_unknown ||
2774 C->getNameModifier() == OMPD_cancel) {
2775 IfCond = C->getCondition();
2776 break;
2777 }
2778 }
2779 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002780 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002781}
2782
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002783CodeGenFunction::JumpDest
2784CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2785 if (Kind == OMPD_parallel || Kind == OMPD_task)
2786 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002787 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002788 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002789 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002790}
Michael Wong65f367f2015-07-21 13:44:28 +00002791
2792// Generate the instructions for '#pragma omp target data' directive.
2793void CodeGenFunction::EmitOMPTargetDataDirective(
2794 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002795 // emit the code inside the construct for now
2796 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002797 CGM.getOpenMPRuntime().emitInlinedDirective(
2798 *this, OMPD_target_data,
2799 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002800}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002801
Samuel Antaodf67fc42016-01-19 19:15:56 +00002802void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2803 const OMPTargetEnterDataDirective &S) {
2804 // TODO: codegen for target enter data.
2805}
2806
Samuel Antao72590762016-01-19 20:04:50 +00002807void CodeGenFunction::EmitOMPTargetExitDataDirective(
2808 const OMPTargetExitDataDirective &S) {
2809 // TODO: codegen for target exit data.
2810}
2811
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002812void CodeGenFunction::EmitOMPTargetParallelDirective(
2813 const OMPTargetParallelDirective &S) {
2814 // TODO: codegen for target parallel.
2815}
2816
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002817void CodeGenFunction::EmitOMPTargetParallelForDirective(
2818 const OMPTargetParallelForDirective &S) {
2819 // TODO: codegen for target parallel for.
2820}
2821
Alexey Bataev49f6e782015-12-01 04:18:41 +00002822void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2823 // emit the code inside the construct for now
2824 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2825 CGM.getOpenMPRuntime().emitInlinedDirective(
2826 *this, OMPD_taskloop,
2827 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2828}
2829
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002830void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2831 const OMPTaskLoopSimdDirective &S) {
2832 // emit the code inside the construct for now
2833 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2834 CGM.getOpenMPRuntime().emitInlinedDirective(
2835 *this, OMPD_taskloop_simd,
2836 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2837}
2838