blob: 30385cd8b92bf3359da30e2b5c4e34f202b8986e [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 Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
29class OMPLexicalScope {
30 CodeGenFunction::LexicalScope Scope;
31 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
32 for (const auto *C : S.clauses()) {
33 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
34 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000035 for (const auto *I : PreInit->decls()) {
36 if (!I->hasAttr<OMPCaptureNoInitAttr>())
37 CGF.EmitVarDecl(cast<VarDecl>(*I));
38 else {
39 CodeGenFunction::AutoVarEmission Emission =
40 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
41 CGF.EmitAutoVarCleanups(Emission);
42 }
43 }
Alexey Bataev3392d762016-02-16 11:18:12 +000044 }
45 }
46 }
47 }
48
Alexey Bataev3392d762016-02-16 11:18:12 +000049public:
50 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
51 : Scope(CGF, S.getSourceRange()) {
52 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000053 }
54};
55} // namespace
56
Alexey Bataev1189bd02016-01-26 12:20:39 +000057llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
58 auto &C = getContext();
59 llvm::Value *Size = nullptr;
60 auto SizeInChars = C.getTypeSizeInChars(Ty);
61 if (SizeInChars.isZero()) {
62 // getTypeSizeInChars() returns 0 for a VLA.
63 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
64 llvm::Value *ArraySize;
65 std::tie(ArraySize, Ty) = getVLASize(VAT);
66 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
67 }
68 SizeInChars = C.getTypeSizeInChars(Ty);
69 if (SizeInChars.isZero())
70 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
71 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
72 } else
73 Size = CGM.getSize(SizeInChars);
74 return Size;
75}
76
Alexey Bataev2377fe92015-09-10 08:12:02 +000077void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000078 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000079 const RecordDecl *RD = S.getCapturedRecordDecl();
80 auto CurField = RD->field_begin();
81 auto CurCap = S.captures().begin();
82 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
83 E = S.capture_init_end();
84 I != E; ++I, ++CurField, ++CurCap) {
85 if (CurField->hasCapturedVLAType()) {
86 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000087 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000088 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000089 } else if (CurCap->capturesThis())
90 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000091 else if (CurCap->capturesVariableByCopy())
92 CapturedVars.push_back(
93 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
94 else {
95 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000096 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000097 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000098 }
99}
100
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000101static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
102 StringRef Name, LValue AddrLV,
103 bool isReferenceType = false) {
104 ASTContext &Ctx = CGF.getContext();
105
106 auto *CastedPtr = CGF.EmitScalarConversion(
107 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
108 Ctx.getPointerType(DstType), SourceLocation());
109 auto TmpAddr =
110 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
111 .getAddress();
112
113 // If we are dealing with references we need to return the address of the
114 // reference instead of the reference of the value.
115 if (isReferenceType) {
116 QualType RefType = Ctx.getLValueReferenceType(DstType);
117 auto *RefVal = TmpAddr.getPointer();
118 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
119 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
120 CGF.EmitScalarInit(RefVal, TmpLVal);
121 }
122
123 return TmpAddr;
124}
125
Alexey Bataev2377fe92015-09-10 08:12:02 +0000126llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000127CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000128 assert(
129 CapturedStmtInfo &&
130 "CapturedStmtInfo should be set when generating the captured function");
131 const CapturedDecl *CD = S.getCapturedDecl();
132 const RecordDecl *RD = S.getCapturedRecordDecl();
133 assert(CD->hasBody() && "missing CapturedDecl body");
134
135 // Build the argument list.
136 ASTContext &Ctx = CGM.getContext();
137 FunctionArgList Args;
138 Args.append(CD->param_begin(),
139 std::next(CD->param_begin(), CD->getContextParamPosition()));
140 auto I = S.captures().begin();
141 for (auto *FD : RD->fields()) {
142 QualType ArgType = FD->getType();
143 IdentifierInfo *II = nullptr;
144 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000145
146 // If this is a capture by copy and the type is not a pointer, the outlined
147 // function argument type should be uintptr and the value properly casted to
148 // uintptr. This is necessary given that the runtime library is only able to
149 // deal with pointers. We can pass in the same way the VLA type sizes to the
150 // outlined function.
151 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
152 I->capturesVariableArrayType())
153 ArgType = Ctx.getUIntPtrType();
154
155 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000156 CapVar = I->getCapturedVar();
157 II = CapVar->getIdentifier();
158 } else if (I->capturesThis())
159 II = &getContext().Idents.get("this");
160 else {
161 assert(I->capturesVariableArrayType());
162 II = &getContext().Idents.get("vla");
163 }
164 if (ArgType->isVariablyModifiedType())
165 ArgType = getContext().getVariableArrayDecayedType(ArgType);
166 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
167 FD->getLocation(), II, ArgType));
168 ++I;
169 }
170 Args.append(
171 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
172 CD->param_end());
173
174 // Create the function declaration.
175 FunctionType::ExtInfo ExtInfo;
176 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000177 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000178 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 Bataeva839ddd2016-03-17 10:19:46 +0000314/// Check if the combiner is a call to UDR combiner and if it is so return the
315/// UDR decl used for reduction.
316static const OMPDeclareReductionDecl *
317getReductionInit(const Expr *ReductionOp) {
318 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
319 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
320 if (auto *DRE =
321 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
322 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
323 return DRD;
324 return nullptr;
325}
326
327static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
328 const OMPDeclareReductionDecl *DRD,
329 const Expr *InitOp,
330 Address Private, Address Original,
331 QualType Ty) {
332 if (DRD->getInitializer()) {
333 std::pair<llvm::Function *, llvm::Function *> Reduction =
334 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
335 auto *CE = cast<CallExpr>(InitOp);
336 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
337 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
338 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
339 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
340 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
341 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
342 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
343 [=]() -> Address { return Private; });
344 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
345 [=]() -> Address { return Original; });
346 (void)PrivateScope.Privatize();
347 RValue Func = RValue::get(Reduction.second);
348 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
349 CGF.EmitIgnoredExpr(InitOp);
350 } else {
351 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
352 auto *GV = new llvm::GlobalVariable(
353 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
354 llvm::GlobalValue::PrivateLinkage, Init, ".init");
355 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
356 RValue InitRVal;
357 switch (CGF.getEvaluationKind(Ty)) {
358 case TEK_Scalar:
359 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
360 break;
361 case TEK_Complex:
362 InitRVal =
363 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
364 break;
365 case TEK_Aggregate:
366 InitRVal = RValue::getAggregate(LV.getAddress());
367 break;
368 }
369 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
370 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
371 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
372 /*IsInitializer=*/false);
373 }
374}
375
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000376/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000377/// \param DestAddr Address of the array.
378/// \param Type Type of array.
379/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000380/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000381static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000382 QualType Type, const Expr *Init,
383 Address SrcAddr = Address::invalid()) {
384 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000385 // Perform element-by-element initialization.
386 QualType ElementTy;
387
388 // Drill down to the base element type on both arrays.
389 auto ArrayTy = Type->getAsArrayTypeUnsafe();
390 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
391 DestAddr =
392 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000393 if (DRD)
394 SrcAddr =
395 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000396
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000397 llvm::Value *SrcBegin = nullptr;
398 if (DRD)
399 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000400 auto DestBegin = DestAddr.getPointer();
401 // Cast from pointer to array type to pointer to single element.
402 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
403 // The basic structure here is a while-do loop.
404 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
405 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
406 auto IsEmpty =
407 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
408 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
409
410 // Enter the loop body, making that address the current address.
411 auto EntryBB = CGF.Builder.GetInsertBlock();
412 CGF.EmitBlock(BodyBB);
413
414 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
415
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000416 llvm::PHINode *SrcElementPHI = nullptr;
417 Address SrcElementCurrent = Address::invalid();
418 if (DRD) {
419 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
420 "omp.arraycpy.srcElementPast");
421 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
422 SrcElementCurrent =
423 Address(SrcElementPHI,
424 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
425 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000426 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
427 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
428 DestElementPHI->addIncoming(DestBegin, EntryBB);
429 Address DestElementCurrent =
430 Address(DestElementPHI,
431 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
432
433 // Emit copy.
434 {
435 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000436 if (DRD) {
437 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
438 SrcElementCurrent, ElementTy);
439 } else
440 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
441 /*IsInitializer=*/false);
442 }
443
444 if (DRD) {
445 // Shift the address forward by one element.
446 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
447 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
448 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000449 }
450
451 // Shift the address forward by one element.
452 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
453 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
454 // Check whether we've reached the end.
455 auto Done =
456 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
457 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
458 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
459
460 // Done.
461 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
462}
463
John McCall7f416cc2015-09-08 08:05:57 +0000464void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
465 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000466 const VarDecl *SrcVD, const Expr *Copy) {
467 if (OriginalType->isArrayType()) {
468 auto *BO = dyn_cast<BinaryOperator>(Copy);
469 if (BO && BO->getOpcode() == BO_Assign) {
470 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000471 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000472 } else {
473 // For arrays with complex element types perform element by element
474 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000475 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000476 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000477 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000478 // Working with the single array element, so have to remap
479 // destination and source variables to corresponding array
480 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000481 CodeGenFunction::OMPPrivateScope Remap(*this);
482 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000483 return DestElement;
484 });
485 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000486 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000487 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000488 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000489 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000490 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000491 } else {
492 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000493 CodeGenFunction::OMPPrivateScope Remap(*this);
494 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
495 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000496 (void)Remap.Privatize();
497 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000498 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000499 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000500}
501
Alexey Bataev69c62a92015-04-15 04:52:20 +0000502bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
503 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000504 if (!HaveInsertPoint())
505 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000506 bool FirstprivateIsLastprivate = false;
507 llvm::DenseSet<const VarDecl *> Lastprivates;
508 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
509 for (const auto *D : C->varlists())
510 Lastprivates.insert(
511 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
512 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000513 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000514 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000515 auto IRef = C->varlist_begin();
516 auto InitsRef = C->inits().begin();
517 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000518 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000519 FirstprivateIsLastprivate =
520 FirstprivateIsLastprivate ||
521 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
522 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000523 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
524 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
525 bool IsRegistered;
526 DeclRefExpr DRE(
527 const_cast<VarDecl *>(OrigVD),
528 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
529 OrigVD) != nullptr,
530 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000531 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000532 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000533 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000534 // Emit VarDecl with copy init for arrays.
535 // Get the address of the original variable captured in current
536 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000537 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000538 auto Emission = EmitAutoVarAlloca(*VD);
539 auto *Init = VD->getInit();
540 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
541 // Perform simple memcpy.
542 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000543 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000544 } else {
545 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000546 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000547 [this, VDInit, Init](Address DestElement,
548 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000549 // Clean up any temporaries needed by the initialization.
550 RunCleanupsScope InitScope(*this);
551 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000552 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000553 EmitAnyExprToMem(Init, DestElement,
554 Init->getType().getQualifiers(),
555 /*IsInitializer*/ false);
556 LocalDeclMap.erase(VDInit);
557 });
558 }
559 EmitAutoVarCleanups(Emission);
560 return Emission.getAllocatedAddress();
561 });
562 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000563 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000564 // Emit private VarDecl with copy init.
565 // Remap temp VDInit variable to the address of the original
566 // variable
567 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000568 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000569 EmitDecl(*VD);
570 LocalDeclMap.erase(VDInit);
571 return GetAddrOfLocalVar(VD);
572 });
573 }
574 assert(IsRegistered &&
575 "firstprivate var already registered as private");
576 // Silence the warning about unused variable.
577 (void)IsRegistered;
578 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000579 ++IRef;
580 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000581 }
582 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000583 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000584}
585
Alexey Bataev03b340a2014-10-21 03:16:40 +0000586void CodeGenFunction::EmitOMPPrivateClause(
587 const OMPExecutableDirective &D,
588 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000589 if (!HaveInsertPoint())
590 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000591 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000592 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000593 auto IRef = C->varlist_begin();
594 for (auto IInit : C->private_copies()) {
595 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000596 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
597 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
598 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000599 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000600 // Emit private VarDecl with copy init.
601 EmitDecl(*VD);
602 return GetAddrOfLocalVar(VD);
603 });
604 assert(IsRegistered && "private var already registered as private");
605 // Silence the warning about unused variable.
606 (void)IsRegistered;
607 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000608 ++IRef;
609 }
610 }
611}
612
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000613bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000614 if (!HaveInsertPoint())
615 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000616 // threadprivate_var1 = master_threadprivate_var1;
617 // operator=(threadprivate_var2, master_threadprivate_var2);
618 // ...
619 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000620 llvm::DenseSet<const VarDecl *> CopiedVars;
621 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000622 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000623 auto IRef = C->varlist_begin();
624 auto ISrcRef = C->source_exprs().begin();
625 auto IDestRef = C->destination_exprs().begin();
626 for (auto *AssignOp : C->assignment_ops()) {
627 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000628 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000629 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000630 // Get the address of the master variable. If we are emitting code with
631 // TLS support, the address is passed from the master as field in the
632 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000633 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000634 if (getLangOpts().OpenMPUseTLS &&
635 getContext().getTargetInfo().isTLSSupported()) {
636 assert(CapturedStmtInfo->lookup(VD) &&
637 "Copyin threadprivates should have been captured!");
638 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
639 VK_LValue, (*IRef)->getExprLoc());
640 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000641 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000642 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000643 MasterAddr =
644 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
645 : CGM.GetAddrOfGlobal(VD),
646 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000647 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000648 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000649 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000650 if (CopiedVars.size() == 1) {
651 // At first check if current thread is a master thread. If it is, no
652 // need to copy data.
653 CopyBegin = createBasicBlock("copyin.not.master");
654 CopyEnd = createBasicBlock("copyin.not.master.end");
655 Builder.CreateCondBr(
656 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000657 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
658 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000659 CopyBegin, CopyEnd);
660 EmitBlock(CopyBegin);
661 }
662 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
663 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000664 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000665 }
666 ++IRef;
667 ++ISrcRef;
668 ++IDestRef;
669 }
670 }
671 if (CopyEnd) {
672 // Exit out of copying procedure for non-master thread.
673 EmitBlock(CopyEnd, /*IsFinished=*/true);
674 return true;
675 }
676 return false;
677}
678
Alexey Bataev38e89532015-04-16 04:54:05 +0000679bool CodeGenFunction::EmitOMPLastprivateClauseInit(
680 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000681 if (!HaveInsertPoint())
682 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000683 bool HasAtLeastOneLastprivate = false;
684 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000685 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000686 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000687 auto IRef = C->varlist_begin();
688 auto IDestRef = C->destination_exprs().begin();
689 for (auto *IInit : C->private_copies()) {
690 // Keep the address of the original variable for future update at the end
691 // of the loop.
692 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
693 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
694 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000695 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000696 DeclRefExpr DRE(
697 const_cast<VarDecl *>(OrigVD),
698 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
699 OrigVD) != nullptr,
700 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
701 return EmitLValue(&DRE).getAddress();
702 });
703 // Check if the variable is also a firstprivate: in this case IInit is
704 // not generated. Initialization of this variable will happen in codegen
705 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000706 if (IInit) {
707 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
708 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000709 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000710 // Emit private VarDecl with copy init.
711 EmitDecl(*VD);
712 return GetAddrOfLocalVar(VD);
713 });
714 assert(IsRegistered &&
715 "lastprivate var already registered as private");
716 (void)IsRegistered;
717 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000718 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000719 ++IRef;
720 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000721 }
722 }
723 return HasAtLeastOneLastprivate;
724}
725
726void CodeGenFunction::EmitOMPLastprivateClauseFinal(
727 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000728 if (!HaveInsertPoint())
729 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000730 // Emit following code:
731 // if (<IsLastIterCond>) {
732 // orig_var1 = private_orig_var1;
733 // ...
734 // orig_varn = private_orig_varn;
735 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000736 llvm::BasicBlock *ThenBB = nullptr;
737 llvm::BasicBlock *DoneBB = nullptr;
738 if (IsLastIterCond) {
739 ThenBB = createBasicBlock(".omp.lastprivate.then");
740 DoneBB = createBasicBlock(".omp.lastprivate.done");
741 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
742 EmitBlock(ThenBB);
743 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000744 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000745 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000746 auto IC = LoopDirective->counters().begin();
747 for (auto F : LoopDirective->finals()) {
748 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
749 LoopCountersAndUpdates[D] = F;
750 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000751 }
752 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000753 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
754 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
755 auto IRef = C->varlist_begin();
756 auto ISrcRef = C->source_exprs().begin();
757 auto IDestRef = C->destination_exprs().begin();
758 for (auto *AssignOp : C->assignment_ops()) {
759 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
760 QualType Type = PrivateVD->getType();
761 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
762 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
763 // If lastprivate variable is a loop control variable for loop-based
764 // directive, update its value before copyin back to original
765 // variable.
766 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
767 EmitIgnoredExpr(UpExpr);
768 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
769 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
770 // Get the address of the original variable.
771 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
772 // Get the address of the private variable.
773 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
774 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
775 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000776 Address(Builder.CreateLoad(PrivateAddr),
777 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000778 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000779 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000780 ++IRef;
781 ++ISrcRef;
782 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000783 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000784 if (auto *PostUpdate = C->getPostUpdateExpr())
785 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000786 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000787 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000788 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000789}
790
Alexey Bataev31300ed2016-02-04 11:27:03 +0000791static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
792 LValue BaseLV, llvm::Value *Addr) {
793 Address Tmp = Address::invalid();
794 Address TopTmp = Address::invalid();
795 Address MostTopTmp = Address::invalid();
796 BaseTy = BaseTy.getNonReferenceType();
797 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
798 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
799 Tmp = CGF.CreateMemTemp(BaseTy);
800 if (TopTmp.isValid())
801 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
802 else
803 MostTopTmp = Tmp;
804 TopTmp = Tmp;
805 BaseTy = BaseTy->getPointeeType();
806 }
807 llvm::Type *Ty = BaseLV.getPointer()->getType();
808 if (Tmp.isValid())
809 Ty = Tmp.getElementType();
810 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
811 if (Tmp.isValid()) {
812 CGF.Builder.CreateStore(Addr, Tmp);
813 return MostTopTmp;
814 }
815 return Address(Addr, BaseLV.getAlignment());
816}
817
818static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
819 LValue BaseLV) {
820 BaseTy = BaseTy.getNonReferenceType();
821 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
822 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
823 if (auto *PtrTy = BaseTy->getAs<PointerType>())
824 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
825 else {
826 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
827 BaseTy->castAs<ReferenceType>());
828 }
829 BaseTy = BaseTy->getPointeeType();
830 }
831 return CGF.MakeAddrLValue(
832 Address(
833 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
834 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
835 BaseLV.getAlignment()),
836 BaseLV.getType(), BaseLV.getAlignmentSource());
837}
838
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000839void CodeGenFunction::EmitOMPReductionClauseInit(
840 const OMPExecutableDirective &D,
841 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000842 if (!HaveInsertPoint())
843 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000844 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000845 auto ILHS = C->lhs_exprs().begin();
846 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000847 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000848 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000849 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000850 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000851 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
852 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000853 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000854 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
855 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
856 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
857 Base = TempOASE->getBase()->IgnoreParenImpCasts();
858 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
859 Base = TempASE->getBase()->IgnoreParenImpCasts();
860 auto *DE = cast<DeclRefExpr>(Base);
861 auto *OrigVD = cast<VarDecl>(DE->getDecl());
862 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
863 auto OASELValueUB =
864 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
865 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000866 LValue BaseLValue =
867 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
868 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000869 // Store the address of the original variable associated with the LHS
870 // implicit variable.
871 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
872 return OASELValueLB.getAddress();
873 });
874 // Emit reduction copy.
875 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000876 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000877 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000878 // Emit VarDecl with copy init for arrays.
879 // Get the address of the original variable captured in current
880 // captured region.
881 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
882 OASELValueLB.getPointer());
883 Size = Builder.CreateNUWAdd(
884 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
885 CodeGenFunction::OpaqueValueMapping OpaqueMap(
886 *this, cast<OpaqueValueExpr>(
887 getContext()
888 .getAsVariableArrayType(PrivateVD->getType())
889 ->getSizeExpr()),
890 RValue::get(Size));
891 EmitVariablyModifiedType(PrivateVD->getType());
892 auto Emission = EmitAutoVarAlloca(*PrivateVD);
893 auto Addr = Emission.getAllocatedAddress();
894 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000895 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
896 DRD ? *IRed : Init,
897 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000898 EmitAutoVarCleanups(Emission);
899 // Emit private VarDecl with reduction init.
900 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
901 OASELValueLB.getPointer());
902 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000903 return castToBase(*this, OrigVD->getType(),
904 OASELValueLB.getType(), OriginalBaseLValue,
905 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000906 });
907 assert(IsRegistered && "private var already registered as private");
908 // Silence the warning about unused variable.
909 (void)IsRegistered;
910 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
911 return GetAddrOfLocalVar(PrivateVD);
912 });
913 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
914 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
915 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
916 Base = TempASE->getBase()->IgnoreParenImpCasts();
917 auto *DE = cast<DeclRefExpr>(Base);
918 auto *OrigVD = cast<VarDecl>(DE->getDecl());
919 auto ASELValue = EmitLValue(ASE);
920 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000921 LValue BaseLValue = loadToBegin(
922 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000923 // Store the address of the original variable associated with the LHS
924 // implicit variable.
925 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
926 return ASELValue.getAddress();
927 });
928 // Emit reduction copy.
929 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000930 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000931 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000932 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000933 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
934 auto Addr = Emission.getAllocatedAddress();
935 if (DRD) {
936 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
937 ASELValue.getAddress(),
938 ASELValue.getType());
939 } else
940 EmitAutoVarInit(Emission);
941 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000942 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
943 ASELValue.getPointer());
944 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000945 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
946 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000947 });
948 assert(IsRegistered && "private var already registered as private");
949 // Silence the warning about unused variable.
950 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000951 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
952 return Builder.CreateElementBitCast(
953 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
954 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000955 });
956 } else {
957 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000958 QualType Type = PrivateVD->getType();
959 if (getContext().getAsArrayType(Type)) {
960 // Store the address of the original variable associated with the LHS
961 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000962 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
963 CapturedStmtInfo->lookup(OrigVD) != nullptr,
964 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000965 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000966 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +0000967 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000968 OriginalAddr = Builder.CreateElementBitCast(
969 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
970 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000971 });
972 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
973 if (Type->isVariablyModifiedType()) {
974 CodeGenFunction::OpaqueValueMapping OpaqueMap(
975 *this, cast<OpaqueValueExpr>(
976 getContext()
977 .getAsVariableArrayType(PrivateVD->getType())
978 ->getSizeExpr()),
979 RValue::get(
980 getTypeSize(OrigVD->getType().getNonReferenceType())));
981 EmitVariablyModifiedType(Type);
982 }
983 auto Emission = EmitAutoVarAlloca(*PrivateVD);
984 auto Addr = Emission.getAllocatedAddress();
985 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000986 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
987 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000988 EmitAutoVarCleanups(Emission);
989 return Emission.getAllocatedAddress();
990 });
991 assert(IsRegistered && "private var already registered as private");
992 // Silence the warning about unused variable.
993 (void)IsRegistered;
994 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
995 return Builder.CreateElementBitCast(
996 GetAddrOfLocalVar(PrivateVD),
997 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
998 });
999 } else {
1000 // Store the address of the original variable associated with the LHS
1001 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001002 Address OriginalAddr = Address::invalid();
1003 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1004 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001005 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1006 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1007 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001008 OriginalAddr = EmitLValue(&DRE).getAddress();
1009 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001010 });
1011 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001012 bool IsRegistered = PrivateScope.addPrivate(
1013 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001014 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001015 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1016 auto Addr = Emission.getAllocatedAddress();
1017 if (DRD) {
1018 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1019 OriginalAddr,
1020 PrivateVD->getType());
1021 } else
1022 EmitAutoVarInit(Emission);
1023 EmitAutoVarCleanups(Emission);
1024 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001025 });
1026 assert(IsRegistered && "private var already registered as private");
1027 // Silence the warning about unused variable.
1028 (void)IsRegistered;
1029 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1030 return GetAddrOfLocalVar(PrivateVD);
1031 });
1032 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001033 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001034 ++ILHS;
1035 ++IRHS;
1036 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001037 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001038 }
1039 }
1040}
1041
1042void CodeGenFunction::EmitOMPReductionClauseFinal(
1043 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001044 if (!HaveInsertPoint())
1045 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001046 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001047 llvm::SmallVector<const Expr *, 8> LHSExprs;
1048 llvm::SmallVector<const Expr *, 8> RHSExprs;
1049 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001050 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001051 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001052 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001053 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001054 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1055 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1056 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1057 }
1058 if (HasAtLeastOneReduction) {
1059 // Emit nowait reduction if nowait clause is present or directive is a
1060 // parallel directive (it always has implicit barrier).
1061 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001062 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001063 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001064 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1065 D.getDirectiveKind() == OMPD_simd,
1066 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001067 }
1068}
1069
Alexey Bataev61205072016-03-02 04:57:40 +00001070static void emitPostUpdateForReductionClause(
1071 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1072 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1073 if (!CGF.HaveInsertPoint())
1074 return;
1075 llvm::BasicBlock *DoneBB = nullptr;
1076 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1077 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1078 if (!DoneBB) {
1079 if (auto *Cond = CondGen(CGF)) {
1080 // If the first post-update expression is found, emit conditional
1081 // block if it was requested.
1082 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1083 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1084 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1085 CGF.EmitBlock(ThenBB);
1086 }
1087 }
1088 CGF.EmitIgnoredExpr(PostUpdate);
1089 }
1090 }
1091 if (DoneBB)
1092 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1093}
1094
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001095static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1096 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001097 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001098 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001099 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +00001100 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1101 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001102 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1103 emitParallelOrTeamsOutlinedFunction(S,
1104 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001105 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001106 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001107 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1108 /*IgnoreResultAssign*/ true);
1109 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1110 CGF, NumThreads, NumThreadsClause->getLocStart());
1111 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001112 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +00001113 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001114 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1115 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1116 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001117 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001118 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1119 if (C->getNameModifier() == OMPD_unknown ||
1120 C->getNameModifier() == OMPD_parallel) {
1121 IfCond = C->getCondition();
1122 break;
1123 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001124 }
1125 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001126 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001127}
1128
1129void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001130 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001131 // Emit parallel region as a standalone region.
1132 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1133 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001134 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001135 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1136 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001137 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001138 // propagation master's thread values of threadprivate variables to local
1139 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001140 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1141 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1142 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001143 }
1144 CGF.EmitOMPPrivateClause(S, PrivateScope);
1145 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1146 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001147 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001148 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001149 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001150 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001151 emitPostUpdateForReductionClause(
1152 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001153}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001154
Alexey Bataev0f34da12015-07-02 04:17:07 +00001155void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1156 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001157 RunCleanupsScope BodyScope(*this);
1158 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001159 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001160 EmitIgnoredExpr(I);
1161 }
Alexander Musman3276a272015-03-21 10:12:56 +00001162 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001163 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001164 for (auto U : C->updates()) {
1165 EmitIgnoredExpr(U);
1166 }
1167 }
1168
Alexander Musmana5f070a2014-10-01 06:03:56 +00001169 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001170 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001171 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001172 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001173 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001174 // The end (updates/cleanups).
1175 EmitBlock(Continue.getBlock());
1176 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001177}
1178
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001179void CodeGenFunction::EmitOMPInnerLoop(
1180 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1181 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001182 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1183 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001184 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001185
1186 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001187 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001188 EmitBlock(CondBlock);
1189 LoopStack.push(CondBlock);
1190
1191 // If there are any cleanups between here and the loop-exit scope,
1192 // create a block to stage a loop exit along.
1193 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001194 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001195 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001196
Alexander Musmand196ef22014-10-07 08:57:09 +00001197 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001198
Alexey Bataev2df54a02015-03-12 08:53:29 +00001199 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001200 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001201 if (ExitBlock != LoopExit.getBlock()) {
1202 EmitBlock(ExitBlock);
1203 EmitBranchThroughCleanup(LoopExit);
1204 }
1205
1206 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001207 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001208
1209 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001210 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001211 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1212
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001213 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001214
1215 // Emit "IV = IV + 1" and a back-edge to the condition block.
1216 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001217 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001218 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001219 BreakContinueStack.pop_back();
1220 EmitBranch(CondBlock);
1221 LoopStack.pop();
1222 // Emit the fall-through block.
1223 EmitBlock(LoopExit.getBlock());
1224}
1225
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001226void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001227 if (!HaveInsertPoint())
1228 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001229 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001230 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001231 for (auto Init : C->inits()) {
1232 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001233 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1234 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1235 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1236 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1237 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1238 VD->getInit()->getType(), VK_LValue,
1239 VD->getInit()->getExprLoc());
1240 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1241 VD->getType()),
1242 /*capturedByInit=*/false);
1243 EmitAutoVarCleanups(Emission);
1244 } else
1245 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001246 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001247 // Emit the linear steps for the linear clauses.
1248 // If a step is not constant, it is pre-calculated before the loop.
1249 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1250 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001251 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001252 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001253 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001254 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001255 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001256}
1257
Alexey Bataevef549a82016-03-09 09:49:09 +00001258static void emitLinearClauseFinal(
1259 CodeGenFunction &CGF, const OMPLoopDirective &D,
1260 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001261 if (!CGF.HaveInsertPoint())
1262 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001263 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001264 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001265 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001266 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001267 for (auto F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001268 if (!DoneBB) {
1269 if (auto *Cond = CondGen(CGF)) {
1270 // If the first post-update expression is found, emit conditional
1271 // block if it was requested.
1272 auto *ThenBB = CGF.createBasicBlock(".omp.linear.pu");
1273 DoneBB = CGF.createBasicBlock(".omp.linear.pu.done");
1274 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1275 CGF.EmitBlock(ThenBB);
1276 }
1277 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001278 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1279 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001280 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001281 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001282 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001283 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001284 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001285 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001286 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001287 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001288 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001289 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001290 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataevef549a82016-03-09 09:49:09 +00001291 CGF.EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001292 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001293 if (DoneBB)
1294 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001295}
1296
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001297static void emitAlignedClause(CodeGenFunction &CGF,
1298 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001299 if (!CGF.HaveInsertPoint())
1300 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001301 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001302 unsigned ClauseAlignment = 0;
1303 if (auto AlignmentExpr = Clause->getAlignment()) {
1304 auto AlignmentCI =
1305 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1306 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001307 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001308 for (auto E : Clause->varlists()) {
1309 unsigned Alignment = ClauseAlignment;
1310 if (Alignment == 0) {
1311 // OpenMP [2.8.1, Description]
1312 // If no optional parameter is specified, implementation-defined default
1313 // alignments for SIMD instructions on the target platforms are assumed.
1314 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001315 CGF.getContext()
1316 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1317 E->getType()->getPointeeType()))
1318 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001319 }
1320 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1321 "alignment is not power of 2");
1322 if (Alignment != 0) {
1323 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1324 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1325 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001326 }
1327 }
1328}
1329
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001330static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001331 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001332 ArrayRef<Expr *> Counters,
1333 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001334 if (!CGF.HaveInsertPoint())
1335 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001336 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001337 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001338 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1339 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001340 Address Addr = Address::invalid();
1341 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001342 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001343 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001344 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001345 Addr = VarEmission.getAllocatedAddress();
1346 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001347 });
John McCall7f416cc2015-09-08 08:05:57 +00001348 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001349 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001350 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001351}
1352
Alexey Bataev62dbb972015-04-22 11:59:37 +00001353static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1354 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1355 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001356 if (!CGF.HaveInsertPoint())
1357 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001358 {
1359 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001360 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1361 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001362 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001363 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001364 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001365 CGF.EmitIgnoredExpr(I);
1366 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001367 }
1368 // Check that loop is executed at least one time.
1369 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1370}
1371
Alexander Musman3276a272015-03-21 10:12:56 +00001372static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001373emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001374 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001375 if (!CGF.HaveInsertPoint())
1376 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001377 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001378 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001379 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001380 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1381 auto *PrivateVD =
1382 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001383 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001384 // Emit private VarDecl with copy init.
1385 CGF.EmitVarDecl(*PrivateVD);
1386 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001387 });
1388 assert(IsRegistered && "linear var already registered as private");
1389 // Silence the warning about unused variable.
1390 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001391 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001392 }
1393 }
1394}
1395
Alexey Bataev45bfad52015-08-21 12:19:04 +00001396static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001397 const OMPExecutableDirective &D,
1398 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001399 if (!CGF.HaveInsertPoint())
1400 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001401 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001402 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1403 /*ignoreResult=*/true);
1404 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1405 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1406 // In presence of finite 'safelen', it may be unsafe to mark all
1407 // the memory instructions parallel, because loop-carried
1408 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001409 if (!IsMonotonic)
1410 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001411 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001412 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1413 /*ignoreResult=*/true);
1414 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001415 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001416 // In presence of finite 'safelen', it may be unsafe to mark all
1417 // the memory instructions parallel, because loop-carried
1418 // dependences of 'safelen' iterations are possible.
1419 CGF.LoopStack.setParallel(false);
1420 }
1421}
1422
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001423void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1424 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001425 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001426 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001427 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001428 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001429}
1430
Alexey Bataevef549a82016-03-09 09:49:09 +00001431void CodeGenFunction::EmitOMPSimdFinal(
1432 const OMPLoopDirective &D,
1433 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001434 if (!HaveInsertPoint())
1435 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001436 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001437 auto IC = D.counters().begin();
1438 for (auto F : D.finals()) {
1439 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001440 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001441 if (!DoneBB) {
1442 if (auto *Cond = CondGen(*this)) {
1443 // If the first post-update expression is found, emit conditional
1444 // block if it was requested.
1445 auto *ThenBB = createBasicBlock(".omp.final.then");
1446 DoneBB = createBasicBlock(".omp.final.done");
1447 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1448 EmitBlock(ThenBB);
1449 }
1450 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001451 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1452 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1453 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001454 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001455 OMPPrivateScope VarScope(*this);
1456 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001457 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001458 (void)VarScope.Privatize();
1459 EmitIgnoredExpr(F);
1460 }
1461 ++IC;
1462 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001463 if (DoneBB)
1464 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001465}
1466
Alexander Musman515ad8c2014-05-22 08:54:05 +00001467void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001468 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001469 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001470 // for (IV in 0..LastIteration) BODY;
1471 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001472 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001473 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001474
Alexey Bataev62dbb972015-04-22 11:59:37 +00001475 // Emit: if (PreCond) - begin.
1476 // If the condition constant folds and can be elided, avoid emitting the
1477 // whole loop.
1478 bool CondConstant;
1479 llvm::BasicBlock *ContBlock = nullptr;
1480 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1481 if (!CondConstant)
1482 return;
1483 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001484 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1485 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001486 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1487 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001488 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001489 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001490 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001491
1492 // Emit the loop iteration variable.
1493 const Expr *IVExpr = S.getIterationVariable();
1494 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1495 CGF.EmitVarDecl(*IVDecl);
1496 CGF.EmitIgnoredExpr(S.getInit());
1497
1498 // Emit the iterations count variable.
1499 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001500 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001501 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1502 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1503 // Emit calculation of the iterations count.
1504 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001505 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001506
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001507 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001508
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001509 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001510 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001511 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001512 {
1513 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001514 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1515 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001516 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001517 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001518 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001519 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001520 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001521 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1522 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001523 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001524 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001525 CGF.EmitStopPoint(&S);
1526 },
1527 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001528 // Emit final copy of the lastprivate variables at the end of loops.
1529 if (HasLastprivateClause) {
1530 CGF.EmitOMPLastprivateClauseFinal(S);
1531 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001532 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001533 emitPostUpdateForReductionClause(
1534 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001535 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001536 CGF.EmitOMPSimdFinal(
1537 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1538 emitLinearClauseFinal(
1539 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001540 // Emit: if (PreCond) - end.
1541 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001542 CGF.EmitBranch(ContBlock);
1543 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001544 }
1545 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001546 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001547}
1548
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001549void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001550 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1551 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001552 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001553
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001554 const Expr *IVExpr = S.getIterationVariable();
1555 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1556 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1557
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001558 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1559
1560 // Start the loop with a block that tests the condition.
1561 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1562 EmitBlock(CondBlock);
1563 LoopStack.push(CondBlock);
1564
1565 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001566 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001567 // UB = min(UB, GlobalUB)
1568 EmitIgnoredExpr(S.getEnsureUpperBound());
1569 // IV = LB
1570 EmitIgnoredExpr(S.getInit());
1571 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001572 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001573 } else {
1574 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1575 IL, LB, UB, ST);
1576 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001577
1578 // If there are any cleanups between here and the loop-exit scope,
1579 // create a block to stage a loop exit along.
1580 auto ExitBlock = LoopExit.getBlock();
1581 if (LoopScope.requiresCleanups())
1582 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1583
1584 auto LoopBody = createBasicBlock("omp.dispatch.body");
1585 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1586 if (ExitBlock != LoopExit.getBlock()) {
1587 EmitBlock(ExitBlock);
1588 EmitBranchThroughCleanup(LoopExit);
1589 }
1590 EmitBlock(LoopBody);
1591
Alexander Musman92bdaab2015-03-12 13:37:50 +00001592 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1593 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001594 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001595 EmitIgnoredExpr(S.getInit());
1596
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001597 // Create a block for the increment.
1598 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1599 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1600
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001601 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1602 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001603 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1604 LoopStack.setParallel(!IsMonotonic);
1605 else
1606 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001607
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001608 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001609 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1610 [&S, LoopExit](CodeGenFunction &CGF) {
1611 CGF.EmitOMPLoopBody(S, LoopExit);
1612 CGF.EmitStopPoint(&S);
1613 },
1614 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1615 if (Ordered) {
1616 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1617 CGF, Loc, IVSize, IVSigned);
1618 }
1619 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001620
1621 EmitBlock(Continue.getBlock());
1622 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001623 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001624 // Emit "LB = LB + Stride", "UB = UB + Stride".
1625 EmitIgnoredExpr(S.getNextLowerBound());
1626 EmitIgnoredExpr(S.getNextUpperBound());
1627 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001628
1629 EmitBranch(CondBlock);
1630 LoopStack.pop();
1631 // Emit the fall-through block.
1632 EmitBlock(LoopExit.getBlock());
1633
1634 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001635 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001636 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001637
1638}
1639
1640void CodeGenFunction::EmitOMPForOuterLoop(
1641 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1642 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1643 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1644 auto &RT = CGM.getOpenMPRuntime();
1645
1646 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1647 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1648
1649 assert((Ordered ||
1650 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1651 "static non-chunked schedule does not need outer loop");
1652
1653 // Emit outer loop.
1654 //
1655 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1656 // When schedule(dynamic,chunk_size) is specified, the iterations are
1657 // distributed to threads in the team in chunks as the threads request them.
1658 // Each thread executes a chunk of iterations, then requests another chunk,
1659 // until no chunks remain to be distributed. Each chunk contains chunk_size
1660 // iterations, except for the last chunk to be distributed, which may have
1661 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1662 //
1663 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1664 // to threads in the team in chunks as the executing threads request them.
1665 // Each thread executes a chunk of iterations, then requests another chunk,
1666 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1667 // each chunk is proportional to the number of unassigned iterations divided
1668 // by the number of threads in the team, decreasing to 1. For a chunk_size
1669 // with value k (greater than 1), the size of each chunk is determined in the
1670 // same way, with the restriction that the chunks do not contain fewer than k
1671 // iterations (except for the last chunk to be assigned, which may have fewer
1672 // than k iterations).
1673 //
1674 // When schedule(auto) is specified, the decision regarding scheduling is
1675 // delegated to the compiler and/or runtime system. The programmer gives the
1676 // implementation the freedom to choose any possible mapping of iterations to
1677 // threads in the team.
1678 //
1679 // When schedule(runtime) is specified, the decision regarding scheduling is
1680 // deferred until run time, and the schedule and chunk size are taken from the
1681 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1682 // implementation defined
1683 //
1684 // while(__kmpc_dispatch_next(&LB, &UB)) {
1685 // idx = LB;
1686 // while (idx <= UB) { BODY; ++idx;
1687 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1688 // } // inner loop
1689 // }
1690 //
1691 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1692 // When schedule(static, chunk_size) is specified, iterations are divided into
1693 // chunks of size chunk_size, and the chunks are assigned to the threads in
1694 // the team in a round-robin fashion in the order of the thread number.
1695 //
1696 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1697 // while (idx <= UB) { BODY; ++idx; } // inner loop
1698 // LB = LB + ST;
1699 // UB = UB + ST;
1700 // }
1701 //
1702
1703 const Expr *IVExpr = S.getIterationVariable();
1704 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1705 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1706
1707 if (DynamicOrOrdered) {
1708 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1709 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1710 IVSize, IVSigned, Ordered, UBVal, Chunk);
1711 } else {
1712 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1713 Ordered, IL, LB, UB, ST, Chunk);
1714 }
1715
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001716 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001717 ST, IL, Chunk);
1718}
1719
1720void CodeGenFunction::EmitOMPDistributeOuterLoop(
1721 OpenMPDistScheduleClauseKind ScheduleKind,
1722 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1723 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1724
1725 auto &RT = CGM.getOpenMPRuntime();
1726
1727 // Emit outer loop.
1728 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1729 // dynamic
1730 //
1731
1732 const Expr *IVExpr = S.getIterationVariable();
1733 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1734 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1735
1736 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1737 IVSize, IVSigned, /* Ordered = */ false,
1738 IL, LB, UB, ST, Chunk);
1739
1740 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1741 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001742}
1743
Alexander Musmanc6388682014-12-15 07:07:06 +00001744/// \brief Emit a helper variable and return corresponding lvalue.
1745static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1746 const DeclRefExpr *Helper) {
1747 auto VDecl = cast<VarDecl>(Helper->getDecl());
1748 CGF.EmitVarDecl(*VDecl);
1749 return CGF.EmitLValue(Helper);
1750}
1751
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001752namespace {
1753 struct ScheduleKindModifiersTy {
1754 OpenMPScheduleClauseKind Kind;
1755 OpenMPScheduleClauseModifier M1;
1756 OpenMPScheduleClauseModifier M2;
1757 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1758 OpenMPScheduleClauseModifier M1,
1759 OpenMPScheduleClauseModifier M2)
1760 : Kind(Kind), M1(M1), M2(M2) {}
1761 };
1762} // namespace
1763
Alexey Bataev38e89532015-04-16 04:54:05 +00001764bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001765 // Emit the loop iteration variable.
1766 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1767 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1768 EmitVarDecl(*IVDecl);
1769
1770 // Emit the iterations count variable.
1771 // If it is not a variable, Sema decided to calculate iterations count on each
1772 // iteration (e.g., it is foldable into a constant).
1773 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1774 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1775 // Emit calculation of the iterations count.
1776 EmitIgnoredExpr(S.getCalcLastIteration());
1777 }
1778
1779 auto &RT = CGM.getOpenMPRuntime();
1780
Alexey Bataev38e89532015-04-16 04:54:05 +00001781 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001782 // Check pre-condition.
1783 {
1784 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001785 // If the condition constant folds and can be elided, avoid emitting the
1786 // whole loop.
1787 bool CondConstant;
1788 llvm::BasicBlock *ContBlock = nullptr;
1789 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1790 if (!CondConstant)
1791 return false;
1792 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001793 auto *ThenBlock = createBasicBlock("omp.precond.then");
1794 ContBlock = createBasicBlock("omp.precond.end");
1795 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001796 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001797 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001798 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001799 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001800
1801 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001802 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001803 // Emit helper vars inits.
1804 LValue LB =
1805 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1806 LValue UB =
1807 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1808 LValue ST =
1809 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1810 LValue IL =
1811 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1812
Alexander Musmanc6388682014-12-15 07:07:06 +00001813 // Emit 'then' code.
1814 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001815 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001816 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1817 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001818 // initialization of firstprivate variables and post-update of
1819 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001820 CGM.getOpenMPRuntime().emitBarrierCall(
1821 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1822 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001823 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001824 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001825 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001826 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001827 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1828 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001829 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001830 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001831
1832 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001833 llvm::Value *Chunk = nullptr;
1834 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1835 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1836 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1837 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1838 ScheduleKind = C->getScheduleKind();
1839 M1 = C->getFirstScheduleModifier();
1840 M2 = C->getSecondScheduleModifier();
1841 if (const auto *Ch = C->getChunkSize()) {
1842 Chunk = EmitScalarExpr(Ch);
1843 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1844 S.getIterationVariable()->getType(),
1845 S.getLocStart());
1846 }
1847 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001848 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1849 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001850 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001851 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1852 // If the static schedule kind is specified or if the ordered clause is
1853 // specified, and if no monotonic modifier is specified, the effect will
1854 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001855 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001856 /* Chunked */ Chunk != nullptr) &&
1857 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001858 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1859 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001860 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1861 // When no chunk_size is specified, the iteration space is divided into
1862 // chunks that are approximately equal in size, and at most one chunk is
1863 // distributed to each thread. Note that the size of the chunks is
1864 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001865 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1866 IVSize, IVSigned, Ordered,
1867 IL.getAddress(), LB.getAddress(),
1868 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001869 auto LoopExit =
1870 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001871 // UB = min(UB, GlobalUB);
1872 EmitIgnoredExpr(S.getEnsureUpperBound());
1873 // IV = LB;
1874 EmitIgnoredExpr(S.getInit());
1875 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001876 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1877 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001878 [&S, LoopExit](CodeGenFunction &CGF) {
1879 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001880 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001881 },
1882 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001883 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001884 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001885 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001886 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001887 const bool IsMonotonic = Ordered ||
1888 ScheduleKind == OMPC_SCHEDULE_static ||
1889 ScheduleKind == OMPC_SCHEDULE_unknown ||
1890 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1891 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001892 // Emit the outer loop, which requests its work chunk [LB..UB] from
1893 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001894 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001895 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1896 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001897 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001898 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001899 // Emit post-update of the reduction variables if IsLastIter != 0.
1900 emitPostUpdateForReductionClause(
1901 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1902 return CGF.Builder.CreateIsNotNull(
1903 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1904 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001905 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1906 if (HasLastprivateClause)
1907 EmitOMPLastprivateClauseFinal(
1908 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001909 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001910 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001911 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1912 return CGF.Builder.CreateIsNotNull(
1913 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1914 });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001915 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001916 emitLinearClauseFinal(*this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1917 return CGF.Builder.CreateIsNotNull(
1918 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1919 });
Alexander Musmanc6388682014-12-15 07:07:06 +00001920 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001921 if (ContBlock) {
1922 EmitBranch(ContBlock);
1923 EmitBlock(ContBlock, true);
1924 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001925 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001926 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001927}
1928
1929void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001930 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001931 {
1932 OMPLexicalScope Scope(*this, S);
1933 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1934 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1935 };
1936 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1937 S.hasCancel());
1938 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001939
1940 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001941 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001942 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1943 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001944}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001945
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001946void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001947 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001948 {
1949 OMPLexicalScope Scope(*this, S);
1950 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1951 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1952 };
1953 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1954 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001955
1956 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001957 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001958 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1959 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001960}
1961
Alexey Bataev2df54a02015-03-12 08:53:29 +00001962static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1963 const Twine &Name,
1964 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001965 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001966 if (Init)
1967 CGF.EmitScalarInit(Init, LVal);
1968 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001969}
1970
Alexey Bataev3392d762016-02-16 11:18:12 +00001971void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001972 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1973 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001974 bool HasLastprivates = false;
1975 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1976 auto &C = CGF.CGM.getContext();
1977 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1978 // Emit helper vars inits.
1979 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1980 CGF.Builder.getInt32(0));
1981 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1982 : CGF.Builder.getInt32(0);
1983 LValue UB =
1984 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1985 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1986 CGF.Builder.getInt32(1));
1987 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1988 CGF.Builder.getInt32(0));
1989 // Loop counter.
1990 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1991 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1992 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1993 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1994 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1995 // Generate condition for loop.
1996 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1997 OK_Ordinary, S.getLocStart(),
1998 /*fpContractable=*/false);
1999 // Increment for loop counter.
2000 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2001 S.getLocStart());
2002 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2003 // Iterate through all sections and emit a switch construct:
2004 // switch (IV) {
2005 // case 0:
2006 // <SectionStmt[0]>;
2007 // break;
2008 // ...
2009 // case <NumSection> - 1:
2010 // <SectionStmt[<NumSection> - 1]>;
2011 // break;
2012 // }
2013 // .omp.sections.exit:
2014 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2015 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2016 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2017 CS == nullptr ? 1 : CS->size());
2018 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002019 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002020 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002021 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2022 CGF.EmitBlock(CaseBB);
2023 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002024 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002025 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002026 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002027 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002028 } else {
2029 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2030 CGF.EmitBlock(CaseBB);
2031 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2032 CGF.EmitStmt(Stmt);
2033 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002034 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002035 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002036 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002037
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002038 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2039 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002040 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002041 // initialization of firstprivate variables and post-update of lastprivate
2042 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002043 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2044 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2045 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002046 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002047 CGF.EmitOMPPrivateClause(S, LoopScope);
2048 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2049 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2050 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002051
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002052 // Emit static non-chunked loop.
2053 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2054 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
2055 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2056 UB.getAddress(), ST.getAddress());
2057 // UB = min(UB, GlobalUB);
2058 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2059 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2060 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2061 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2062 // IV = LB;
2063 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2064 // while (idx <= UB) { BODY; ++idx; }
2065 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2066 [](CodeGenFunction &) {});
2067 // Tell the runtime we are done.
2068 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
2069 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002070 // Emit post-update of the reduction variables if IsLastIter != 0.
2071 emitPostUpdateForReductionClause(
2072 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2073 return CGF.Builder.CreateIsNotNull(
2074 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2075 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002076
2077 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2078 if (HasLastprivates)
2079 CGF.EmitOMPLastprivateClauseFinal(
2080 S, CGF.Builder.CreateIsNotNull(
2081 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002082 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002083
2084 bool HasCancel = false;
2085 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2086 HasCancel = OSD->hasCancel();
2087 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2088 HasCancel = OPSD->hasCancel();
2089 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2090 HasCancel);
2091 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2092 // clause. Otherwise the barrier will be generated by the codegen for the
2093 // directive.
2094 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002095 // Emit implicit barrier to synchronize threads and avoid data races on
2096 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002097 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2098 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002099 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002100}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002101
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002102void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002103 {
2104 OMPLexicalScope Scope(*this, S);
2105 EmitSections(S);
2106 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002107 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002108 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002109 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2110 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002111 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002112}
2113
2114void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002115 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002116 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2117 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002118 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00002119 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2120 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002121}
2122
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002123void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002124 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002125 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002126 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002127 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002128 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002129 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002130 // Build a list of copyprivate variables along with helper expressions
2131 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002132 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002133 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002134 DestExprs.append(C->destination_exprs().begin(),
2135 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002136 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002137 AssignmentOps.append(C->assignment_ops().begin(),
2138 C->assignment_ops().end());
2139 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002140 {
2141 OMPLexicalScope Scope(*this, S);
2142 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00002143 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002144 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00002145 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00002146 CGF.EmitOMPPrivateClause(S, SingleScope);
2147 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00002148 CGF.EmitStmt(
2149 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2150 };
2151 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2152 CopyprivateVars, DestExprs,
2153 SrcExprs, AssignmentOps);
2154 }
2155 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2156 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002157 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002158 CGM.getOpenMPRuntime().emitBarrierCall(
2159 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002160 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002161 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002162}
2163
Alexey Bataev8d690652014-12-04 07:23:53 +00002164void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002165 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002166 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2167 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002168 };
2169 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002170}
2171
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002172void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002173 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002174 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2175 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002176 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002177 Expr *Hint = nullptr;
2178 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2179 Hint = HintClause->getHint();
2180 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2181 S.getDirectiveName().getAsString(),
2182 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002183}
2184
Alexey Bataev671605e2015-04-13 05:28:11 +00002185void CodeGenFunction::EmitOMPParallelForDirective(
2186 const OMPParallelForDirective &S) {
2187 // Emit directive as a combined directive that consists of two implicit
2188 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002189 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002190 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2191 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002192 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002193 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002194}
2195
Alexander Musmane4e893b2014-09-23 09:33:00 +00002196void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002197 const OMPParallelForSimdDirective &S) {
2198 // Emit directive as a combined directive that consists of two implicit
2199 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002200 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002201 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2202 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002203 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002204 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002205}
2206
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002207void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002208 const OMPParallelSectionsDirective &S) {
2209 // Emit directive as a combined directive that consists of two implicit
2210 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002211 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00002212 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002213 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002214}
2215
Alexey Bataev62b63b12015-03-10 07:28:44 +00002216void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2217 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00002218 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002219 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2220 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2221 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002222 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002223 // The first function argument for tasks is a thread id, the second one is a
2224 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002225 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2226 // Get list of private variables.
2227 llvm::SmallVector<const Expr *, 8> PrivateVars;
2228 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002229 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002230 auto IRef = C->varlist_begin();
2231 for (auto *IInit : C->private_copies()) {
2232 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2233 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2234 PrivateVars.push_back(*IRef);
2235 PrivateCopies.push_back(IInit);
2236 }
2237 ++IRef;
2238 }
2239 }
2240 EmittedAsPrivate.clear();
2241 // Get list of firstprivate variables.
2242 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2243 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2244 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002245 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002246 auto IRef = C->varlist_begin();
2247 auto IElemInitRef = C->inits().begin();
2248 for (auto *IInit : C->private_copies()) {
2249 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2250 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2251 FirstprivateVars.push_back(*IRef);
2252 FirstprivateCopies.push_back(IInit);
2253 FirstprivateInits.push_back(*IElemInitRef);
2254 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002255 ++IRef;
2256 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002257 }
2258 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002259 // Build list of dependences.
2260 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2261 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002262 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002263 for (auto *IRef : C->varlists()) {
2264 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2265 }
2266 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002267 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2268 CodeGenFunction &CGF) {
2269 // Set proper addresses for generated private copies.
2270 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2271 OMPPrivateScope Scope(CGF);
2272 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002273 auto *CopyFn = CGF.Builder.CreateLoad(
2274 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2275 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2276 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002277 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002278 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002279 PrivatePtrs;
2280 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2281 CallArgs.push_back(PrivatesPtr);
2282 for (auto *E : PrivateVars) {
2283 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002284 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002285 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2286 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002287 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002288 }
2289 for (auto *E : FirstprivateVars) {
2290 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002291 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002292 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2293 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002294 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002295 }
2296 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2297 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002298 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2299 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002300 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2301 }
2302 }
2303 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002304 if (*PartId) {
2305 // TODO: emit code for untied tasks.
2306 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002307 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002308 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002309 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2310 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002311 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002312 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002313 // Check if the task is final
2314 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002315 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002316 // If the condition constant folds and can be elided, try to avoid emitting
2317 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002318 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002319 bool CondConstant;
2320 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2321 Final.setInt(CondConstant);
2322 else
2323 Final.setPointer(EvaluateExprAsBool(Cond));
2324 } else {
2325 // By default the task is not final.
2326 Final.setInt(/*IntVal=*/false);
2327 }
2328 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002329 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002330 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2331 if (C->getNameModifier() == OMPD_unknown ||
2332 C->getNameModifier() == OMPD_task) {
2333 IfCond = C->getCondition();
2334 break;
2335 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002336 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002337 CGM.getOpenMPRuntime().emitTaskCall(
2338 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002339 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002340 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002341}
2342
Alexey Bataev9f797f32015-02-05 05:57:51 +00002343void CodeGenFunction::EmitOMPTaskyieldDirective(
2344 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002345 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002346}
2347
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002348void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002349 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002350}
2351
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002352void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2353 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002354}
2355
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002356void CodeGenFunction::EmitOMPTaskgroupDirective(
2357 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002358 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002359 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2360 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002361 };
2362 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2363}
2364
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002365void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002366 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002367 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002368 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2369 FlushClause->varlist_end());
2370 }
2371 return llvm::None;
2372 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002373}
2374
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002375void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2376 // Emit the loop iteration variable.
2377 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2378 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2379 EmitVarDecl(*IVDecl);
2380
2381 // Emit the iterations count variable.
2382 // If it is not a variable, Sema decided to calculate iterations count on each
2383 // iteration (e.g., it is foldable into a constant).
2384 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2385 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2386 // Emit calculation of the iterations count.
2387 EmitIgnoredExpr(S.getCalcLastIteration());
2388 }
2389
2390 auto &RT = CGM.getOpenMPRuntime();
2391
2392 // Check pre-condition.
2393 {
2394 // Skip the entire loop if we don't meet the precondition.
2395 // If the condition constant folds and can be elided, avoid emitting the
2396 // whole loop.
2397 bool CondConstant;
2398 llvm::BasicBlock *ContBlock = nullptr;
2399 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2400 if (!CondConstant)
2401 return;
2402 } else {
2403 auto *ThenBlock = createBasicBlock("omp.precond.then");
2404 ContBlock = createBasicBlock("omp.precond.end");
2405 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2406 getProfileCount(&S));
2407 EmitBlock(ThenBlock);
2408 incrementProfileCounter(&S);
2409 }
2410
2411 // Emit 'then' code.
2412 {
2413 // Emit helper vars inits.
2414 LValue LB =
2415 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2416 LValue UB =
2417 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2418 LValue ST =
2419 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2420 LValue IL =
2421 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2422
2423 OMPPrivateScope LoopScope(*this);
2424 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
2425 S.private_counters());
2426 (void)LoopScope.Privatize();
2427
2428 // Detect the distribute schedule kind and chunk.
2429 llvm::Value *Chunk = nullptr;
2430 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2431 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2432 ScheduleKind = C->getDistScheduleKind();
2433 if (const auto *Ch = C->getChunkSize()) {
2434 Chunk = EmitScalarExpr(Ch);
2435 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2436 S.getIterationVariable()->getType(),
2437 S.getLocStart());
2438 }
2439 }
2440 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2441 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2442
2443 // OpenMP [2.10.8, distribute Construct, Description]
2444 // If dist_schedule is specified, kind must be static. If specified,
2445 // iterations are divided into chunks of size chunk_size, chunks are
2446 // assigned to the teams of the league in a round-robin fashion in the
2447 // order of the team number. When no chunk_size is specified, the
2448 // iteration space is divided into chunks that are approximately equal
2449 // in size, and at most one chunk is distributed to each team of the
2450 // league. The size of the chunks is unspecified in this case.
2451 if (RT.isStaticNonchunked(ScheduleKind,
2452 /* Chunked */ Chunk != nullptr)) {
2453 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2454 IVSize, IVSigned, /* Ordered = */ false,
2455 IL.getAddress(), LB.getAddress(),
2456 UB.getAddress(), ST.getAddress());
2457 auto LoopExit =
2458 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2459 // UB = min(UB, GlobalUB);
2460 EmitIgnoredExpr(S.getEnsureUpperBound());
2461 // IV = LB;
2462 EmitIgnoredExpr(S.getInit());
2463 // while (idx <= UB) { BODY; ++idx; }
2464 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2465 S.getInc(),
2466 [&S, LoopExit](CodeGenFunction &CGF) {
2467 CGF.EmitOMPLoopBody(S, LoopExit);
2468 CGF.EmitStopPoint(&S);
2469 },
2470 [](CodeGenFunction &) {});
2471 EmitBlock(LoopExit.getBlock());
2472 // Tell the runtime we are done.
2473 RT.emitForStaticFinish(*this, S.getLocStart());
2474 } else {
2475 // Emit the outer loop, which requests its work chunk [LB..UB] from
2476 // runtime and runs the inner loop to process it.
2477 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2478 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2479 IL.getAddress(), Chunk);
2480 }
2481 }
2482
2483 // We're now done with the loop, so jump to the continuation block.
2484 if (ContBlock) {
2485 EmitBranch(ContBlock);
2486 EmitBlock(ContBlock, true);
2487 }
2488 }
2489}
2490
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002491void CodeGenFunction::EmitOMPDistributeDirective(
2492 const OMPDistributeDirective &S) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002493 LexicalScope Scope(*this, S.getSourceRange());
2494 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2495 CGF.EmitOMPDistributeLoop(S);
2496 };
2497 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2498 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002499}
2500
Alexey Bataev5f600d62015-09-29 03:48:57 +00002501static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2502 const CapturedStmt *S) {
2503 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2504 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2505 CGF.CapturedStmtInfo = &CapStmtInfo;
2506 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2507 Fn->addFnAttr(llvm::Attribute::NoInline);
2508 return Fn;
2509}
2510
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002511void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002512 if (!S.getAssociatedStmt())
2513 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002514 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002515 auto *C = S.getSingleClause<OMPSIMDClause>();
2516 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2517 if (C) {
2518 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2519 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2520 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2521 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2522 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2523 } else {
2524 CGF.EmitStmt(
2525 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2526 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002527 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002528 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002529}
2530
Alexey Bataevb57056f2015-01-22 06:17:56 +00002531static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002532 QualType SrcType, QualType DestType,
2533 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002534 assert(CGF.hasScalarEvaluationKind(DestType) &&
2535 "DestType must have scalar evaluation kind.");
2536 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2537 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002538 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2539 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002540 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002541 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002542}
2543
2544static CodeGenFunction::ComplexPairTy
2545convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002546 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002547 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2548 "DestType must have complex evaluation kind.");
2549 CodeGenFunction::ComplexPairTy ComplexVal;
2550 if (Val.isScalar()) {
2551 // Convert the input element to the element type of the complex.
2552 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002553 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2554 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002555 ComplexVal = CodeGenFunction::ComplexPairTy(
2556 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2557 } else {
2558 assert(Val.isComplex() && "Must be a scalar or complex.");
2559 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2560 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2561 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002562 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002563 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002564 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002565 }
2566 return ComplexVal;
2567}
2568
Alexey Bataev5e018f92015-04-23 06:35:10 +00002569static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2570 LValue LVal, RValue RVal) {
2571 if (LVal.isGlobalReg()) {
2572 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2573 } else {
2574 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2575 : llvm::Monotonic,
2576 LVal.isVolatile(), /*IsInit=*/false);
2577 }
2578}
2579
Alexey Bataev8524d152016-01-21 12:35:58 +00002580void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2581 QualType RValTy, SourceLocation Loc) {
2582 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002583 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002584 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2585 *this, RVal, RValTy, LVal.getType(), Loc)),
2586 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002587 break;
2588 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002589 EmitStoreOfComplex(
2590 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002591 /*isInit=*/false);
2592 break;
2593 case TEK_Aggregate:
2594 llvm_unreachable("Must be a scalar or complex.");
2595 }
2596}
2597
Alexey Bataevb57056f2015-01-22 06:17:56 +00002598static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2599 const Expr *X, const Expr *V,
2600 SourceLocation Loc) {
2601 // v = x;
2602 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2603 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2604 LValue XLValue = CGF.EmitLValue(X);
2605 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002606 RValue Res = XLValue.isGlobalReg()
2607 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2608 : CGF.EmitAtomicLoad(XLValue, Loc,
2609 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002610 : llvm::Monotonic,
2611 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002612 // OpenMP, 2.12.6, atomic Construct
2613 // Any atomic construct with a seq_cst clause forces the atomically
2614 // performed operation to include an implicit flush operation without a
2615 // list.
2616 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002617 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002618 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002619}
2620
Alexey Bataevb8329262015-02-27 06:33:30 +00002621static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2622 const Expr *X, const Expr *E,
2623 SourceLocation Loc) {
2624 // x = expr;
2625 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002626 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002627 // OpenMP, 2.12.6, atomic Construct
2628 // Any atomic construct with a seq_cst clause forces the atomically
2629 // performed operation to include an implicit flush operation without a
2630 // list.
2631 if (IsSeqCst)
2632 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2633}
2634
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002635static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2636 RValue Update,
2637 BinaryOperatorKind BO,
2638 llvm::AtomicOrdering AO,
2639 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002640 auto &Context = CGF.CGM.getContext();
2641 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002642 // expression is simple and atomic is allowed for the given type for the
2643 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002644 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002645 !Update.getScalarVal()->getType()->isIntegerTy() ||
2646 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2647 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002648 X.getAddress().getElementType())) ||
2649 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002650 !Context.getTargetInfo().hasBuiltinAtomic(
2651 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002652 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002653
2654 llvm::AtomicRMWInst::BinOp RMWOp;
2655 switch (BO) {
2656 case BO_Add:
2657 RMWOp = llvm::AtomicRMWInst::Add;
2658 break;
2659 case BO_Sub:
2660 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002661 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002662 RMWOp = llvm::AtomicRMWInst::Sub;
2663 break;
2664 case BO_And:
2665 RMWOp = llvm::AtomicRMWInst::And;
2666 break;
2667 case BO_Or:
2668 RMWOp = llvm::AtomicRMWInst::Or;
2669 break;
2670 case BO_Xor:
2671 RMWOp = llvm::AtomicRMWInst::Xor;
2672 break;
2673 case BO_LT:
2674 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2675 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2676 : llvm::AtomicRMWInst::Max)
2677 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2678 : llvm::AtomicRMWInst::UMax);
2679 break;
2680 case BO_GT:
2681 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2682 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2683 : llvm::AtomicRMWInst::Min)
2684 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2685 : llvm::AtomicRMWInst::UMin);
2686 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002687 case BO_Assign:
2688 RMWOp = llvm::AtomicRMWInst::Xchg;
2689 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002690 case BO_Mul:
2691 case BO_Div:
2692 case BO_Rem:
2693 case BO_Shl:
2694 case BO_Shr:
2695 case BO_LAnd:
2696 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002697 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002698 case BO_PtrMemD:
2699 case BO_PtrMemI:
2700 case BO_LE:
2701 case BO_GE:
2702 case BO_EQ:
2703 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002704 case BO_AddAssign:
2705 case BO_SubAssign:
2706 case BO_AndAssign:
2707 case BO_OrAssign:
2708 case BO_XorAssign:
2709 case BO_MulAssign:
2710 case BO_DivAssign:
2711 case BO_RemAssign:
2712 case BO_ShlAssign:
2713 case BO_ShrAssign:
2714 case BO_Comma:
2715 llvm_unreachable("Unsupported atomic update operation");
2716 }
2717 auto *UpdateVal = Update.getScalarVal();
2718 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2719 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002720 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002721 X.getType()->hasSignedIntegerRepresentation());
2722 }
John McCall7f416cc2015-09-08 08:05:57 +00002723 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002724 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002725}
2726
Alexey Bataev5e018f92015-04-23 06:35:10 +00002727std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002728 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2729 llvm::AtomicOrdering AO, SourceLocation Loc,
2730 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2731 // Update expressions are allowed to have the following forms:
2732 // x binop= expr; -> xrval + expr;
2733 // x++, ++x -> xrval + 1;
2734 // x--, --x -> xrval - 1;
2735 // x = x binop expr; -> xrval binop expr
2736 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002737 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2738 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002739 if (X.isGlobalReg()) {
2740 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2741 // 'xrval'.
2742 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2743 } else {
2744 // Perform compare-and-swap procedure.
2745 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002746 }
2747 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002748 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002749}
2750
2751static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2752 const Expr *X, const Expr *E,
2753 const Expr *UE, bool IsXLHSInRHSPart,
2754 SourceLocation Loc) {
2755 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2756 "Update expr in 'atomic update' must be a binary operator.");
2757 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2758 // Update expressions are allowed to have the following forms:
2759 // x binop= expr; -> xrval + expr;
2760 // x++, ++x -> xrval + 1;
2761 // x--, --x -> xrval - 1;
2762 // x = x binop expr; -> xrval binop expr
2763 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002764 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002765 LValue XLValue = CGF.EmitLValue(X);
2766 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002767 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002768 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2769 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2770 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2771 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2772 auto Gen =
2773 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2774 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2775 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2776 return CGF.EmitAnyExpr(UE);
2777 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002778 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2779 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2780 // OpenMP, 2.12.6, atomic Construct
2781 // Any atomic construct with a seq_cst clause forces the atomically
2782 // performed operation to include an implicit flush operation without a
2783 // list.
2784 if (IsSeqCst)
2785 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2786}
2787
2788static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002789 QualType SourceType, QualType ResType,
2790 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002791 switch (CGF.getEvaluationKind(ResType)) {
2792 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002793 return RValue::get(
2794 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002795 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002796 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002797 return RValue::getComplex(Res.first, Res.second);
2798 }
2799 case TEK_Aggregate:
2800 break;
2801 }
2802 llvm_unreachable("Must be a scalar or complex.");
2803}
2804
2805static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2806 bool IsPostfixUpdate, const Expr *V,
2807 const Expr *X, const Expr *E,
2808 const Expr *UE, bool IsXLHSInRHSPart,
2809 SourceLocation Loc) {
2810 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2811 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2812 RValue NewVVal;
2813 LValue VLValue = CGF.EmitLValue(V);
2814 LValue XLValue = CGF.EmitLValue(X);
2815 RValue ExprRValue = CGF.EmitAnyExpr(E);
2816 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2817 QualType NewVValType;
2818 if (UE) {
2819 // 'x' is updated with some additional value.
2820 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2821 "Update expr in 'atomic capture' must be a binary operator.");
2822 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2823 // Update expressions are allowed to have the following forms:
2824 // x binop= expr; -> xrval + expr;
2825 // x++, ++x -> xrval + 1;
2826 // x--, --x -> xrval - 1;
2827 // x = x binop expr; -> xrval binop expr
2828 // x = expr Op x; - > expr binop xrval;
2829 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2830 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2831 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2832 NewVValType = XRValExpr->getType();
2833 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2834 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2835 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2836 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2837 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2838 RValue Res = CGF.EmitAnyExpr(UE);
2839 NewVVal = IsPostfixUpdate ? XRValue : Res;
2840 return Res;
2841 };
2842 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2843 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2844 if (Res.first) {
2845 // 'atomicrmw' instruction was generated.
2846 if (IsPostfixUpdate) {
2847 // Use old value from 'atomicrmw'.
2848 NewVVal = Res.second;
2849 } else {
2850 // 'atomicrmw' does not provide new value, so evaluate it using old
2851 // value of 'x'.
2852 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2853 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2854 NewVVal = CGF.EmitAnyExpr(UE);
2855 }
2856 }
2857 } else {
2858 // 'x' is simply rewritten with some 'expr'.
2859 NewVValType = X->getType().getNonReferenceType();
2860 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002861 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002862 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2863 NewVVal = XRValue;
2864 return ExprRValue;
2865 };
2866 // Try to perform atomicrmw xchg, otherwise simple exchange.
2867 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2868 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2869 Loc, Gen);
2870 if (Res.first) {
2871 // 'atomicrmw' instruction was generated.
2872 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2873 }
2874 }
2875 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002876 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002877 // OpenMP, 2.12.6, atomic Construct
2878 // Any atomic construct with a seq_cst clause forces the atomically
2879 // performed operation to include an implicit flush operation without a
2880 // list.
2881 if (IsSeqCst)
2882 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2883}
2884
Alexey Bataevb57056f2015-01-22 06:17:56 +00002885static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002886 bool IsSeqCst, bool IsPostfixUpdate,
2887 const Expr *X, const Expr *V, const Expr *E,
2888 const Expr *UE, bool IsXLHSInRHSPart,
2889 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002890 switch (Kind) {
2891 case OMPC_read:
2892 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2893 break;
2894 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002895 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2896 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002897 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002898 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002899 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2900 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002901 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002902 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2903 IsXLHSInRHSPart, Loc);
2904 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002905 case OMPC_if:
2906 case OMPC_final:
2907 case OMPC_num_threads:
2908 case OMPC_private:
2909 case OMPC_firstprivate:
2910 case OMPC_lastprivate:
2911 case OMPC_reduction:
2912 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002913 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002914 case OMPC_collapse:
2915 case OMPC_default:
2916 case OMPC_seq_cst:
2917 case OMPC_shared:
2918 case OMPC_linear:
2919 case OMPC_aligned:
2920 case OMPC_copyin:
2921 case OMPC_copyprivate:
2922 case OMPC_flush:
2923 case OMPC_proc_bind:
2924 case OMPC_schedule:
2925 case OMPC_ordered:
2926 case OMPC_nowait:
2927 case OMPC_untied:
2928 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002929 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002930 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002931 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002932 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002933 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002934 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002935 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002936 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002937 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002938 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002939 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002940 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002941 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002942 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002943 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002944 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2945 }
2946}
2947
2948void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002949 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002950 OpenMPClauseKind Kind = OMPC_unknown;
2951 for (auto *C : S.clauses()) {
2952 // Find first clause (skip seq_cst clause, if it is first).
2953 if (C->getClauseKind() != OMPC_seq_cst) {
2954 Kind = C->getClauseKind();
2955 break;
2956 }
2957 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002958
2959 const auto *CS =
2960 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002961 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002962 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002963 }
2964 // Processing for statements under 'atomic capture'.
2965 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2966 for (const auto *C : Compound->body()) {
2967 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2968 enterFullExpression(EWC);
2969 }
2970 }
2971 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002972
Alexey Bataev3392d762016-02-16 11:18:12 +00002973 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002974 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2975 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002976 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2977 S.getV(), S.getExpr(), S.getUpdateExpr(),
2978 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002979 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002980 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002981}
2982
Samuel Antaobed3c462015-10-02 16:14:20 +00002983void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002984 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002985 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2986
2987 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002988 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002989
Samuel Antaoee8fb302016-01-06 13:42:12 +00002990 llvm::Function *Fn = nullptr;
2991 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002992
2993 // Check if we have any if clause associated with the directive.
2994 const Expr *IfCond = nullptr;
2995
2996 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2997 IfCond = C->getCondition();
2998 }
2999
3000 // Check if we have any device clause associated with the directive.
3001 const Expr *Device = nullptr;
3002 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3003 Device = C->getDevice();
3004 }
3005
Samuel Antaoee8fb302016-01-06 13:42:12 +00003006 // Check if we have an if clause whose conditional always evaluates to false
3007 // or if we do not have any targets specified. If so the target region is not
3008 // an offload entry point.
3009 bool IsOffloadEntry = true;
3010 if (IfCond) {
3011 bool Val;
3012 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3013 IsOffloadEntry = false;
3014 }
3015 if (CGM.getLangOpts().OMPTargetTriples.empty())
3016 IsOffloadEntry = false;
3017
3018 assert(CurFuncDecl && "No parent declaration for target region!");
3019 StringRef ParentName;
3020 // In case we have Ctors/Dtors we use the complete type variant to produce
3021 // the mangling of the device outlined kernel.
3022 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
3023 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3024 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
3025 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3026 else
3027 ParentName =
3028 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
3029
3030 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3031 IsOffloadEntry);
3032
3033 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003034 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003035}
3036
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003037static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3038 const OMPExecutableDirective &S,
3039 OpenMPDirectiveKind InnermostKind,
3040 const RegionCodeGenTy &CodeGen) {
3041 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3042 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3043 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3044 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3045 emitParallelOrTeamsOutlinedFunction(S,
3046 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003047
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003048 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3049 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3050 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3051 if (NT || TL) {
3052 llvm::Value *NumTeamsVal = (NT) ? CGF.Builder.CreateIntCast(
3053 CGF.EmitScalarExpr(NT->getNumTeams()), CGF.CGM.Int32Ty,
3054 /* isSigned = */ true) :
3055 CGF.Builder.getInt32(0);
3056
3057 llvm::Value *ThreadLimitVal = (TL) ? CGF.Builder.CreateIntCast(
3058 CGF.EmitScalarExpr(TL->getThreadLimit()), CGF.CGM.Int32Ty,
3059 /* isSigned = */ true) :
3060 CGF.Builder.getInt32(0);
3061
3062 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeamsVal,
3063 ThreadLimitVal, S.getLocStart());
3064 }
3065
3066 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3067 CapturedVars);
3068}
3069
3070void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
3071 LexicalScope Scope(*this, S.getSourceRange());
3072 // Emit parallel region as a standalone region.
3073 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3074 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003075 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3076 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003077 (void)PrivateScope.Privatize();
3078 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3079 };
3080 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003081}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003082
3083void CodeGenFunction::EmitOMPCancellationPointDirective(
3084 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003085 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3086 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003087}
3088
Alexey Bataev80909872015-07-02 11:25:17 +00003089void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003090 const Expr *IfCond = nullptr;
3091 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3092 if (C->getNameModifier() == OMPD_unknown ||
3093 C->getNameModifier() == OMPD_cancel) {
3094 IfCond = C->getCondition();
3095 break;
3096 }
3097 }
3098 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003099 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003100}
3101
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003102CodeGenFunction::JumpDest
3103CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
3104 if (Kind == OMPD_parallel || Kind == OMPD_task)
3105 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003106 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003107 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003108 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003109}
Michael Wong65f367f2015-07-21 13:44:28 +00003110
3111// Generate the instructions for '#pragma omp target data' directive.
3112void CodeGenFunction::EmitOMPTargetDataDirective(
3113 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00003114 // emit the code inside the construct for now
3115 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00003116 CGM.getOpenMPRuntime().emitInlinedDirective(
3117 *this, OMPD_target_data,
3118 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00003119}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003120
Samuel Antaodf67fc42016-01-19 19:15:56 +00003121void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3122 const OMPTargetEnterDataDirective &S) {
3123 // TODO: codegen for target enter data.
3124}
3125
Samuel Antao72590762016-01-19 20:04:50 +00003126void CodeGenFunction::EmitOMPTargetExitDataDirective(
3127 const OMPTargetExitDataDirective &S) {
3128 // TODO: codegen for target exit data.
3129}
3130
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003131void CodeGenFunction::EmitOMPTargetParallelDirective(
3132 const OMPTargetParallelDirective &S) {
3133 // TODO: codegen for target parallel.
3134}
3135
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003136void CodeGenFunction::EmitOMPTargetParallelForDirective(
3137 const OMPTargetParallelForDirective &S) {
3138 // TODO: codegen for target parallel for.
3139}
3140
Alexey Bataev49f6e782015-12-01 04:18:41 +00003141void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
3142 // emit the code inside the construct for now
3143 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3144 CGM.getOpenMPRuntime().emitInlinedDirective(
3145 *this, OMPD_taskloop,
3146 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
3147}
3148
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003149void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3150 const OMPTaskLoopSimdDirective &S) {
3151 // emit the code inside the construct for now
3152 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3153 CGM.getOpenMPRuntime().emitInlinedDirective(
3154 *this, OMPD_taskloop_simd,
3155 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
3156}
3157