blob: bd208cb4df54501360339a1f245b0eb83888e3cd [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.
Alexey Bataev14fa1c62016-03-29 05:34:15 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
47
Alexey Bataev3392d762016-02-16 11:18:12 +000048public:
49 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev14fa1c62016-03-29 05:34:15 +000050 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()) {
Alexey Bataev3392d762016-02-16 11:18:12 +000051 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000052 }
53};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000054
Alexey Bataev5a3af132016-03-29 08:58:54 +000055/// Private scope for OpenMP loop-based directives, that supports capturing
56/// of used expression from loop statement.
57class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
58 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
59 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
60 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
61 for (const auto *I : PreInits->decls())
62 CGF.EmitVarDecl(cast<VarDecl>(*I));
63 }
64 }
65 }
66
67public:
68 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
69 : CodeGenFunction::RunCleanupsScope(CGF) {
70 emitPreInitStmt(CGF, S);
71 }
72};
73
Alexey Bataev3392d762016-02-16 11:18:12 +000074} // namespace
75
Alexey Bataev1189bd02016-01-26 12:20:39 +000076llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
77 auto &C = getContext();
78 llvm::Value *Size = nullptr;
79 auto SizeInChars = C.getTypeSizeInChars(Ty);
80 if (SizeInChars.isZero()) {
81 // getTypeSizeInChars() returns 0 for a VLA.
82 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
83 llvm::Value *ArraySize;
84 std::tie(ArraySize, Ty) = getVLASize(VAT);
85 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
86 }
87 SizeInChars = C.getTypeSizeInChars(Ty);
88 if (SizeInChars.isZero())
89 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
90 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
91 } else
92 Size = CGM.getSize(SizeInChars);
93 return Size;
94}
95
Alexey Bataev2377fe92015-09-10 08:12:02 +000096void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000097 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000098 const RecordDecl *RD = S.getCapturedRecordDecl();
99 auto CurField = RD->field_begin();
100 auto CurCap = S.captures().begin();
101 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
102 E = S.capture_init_end();
103 I != E; ++I, ++CurField, ++CurCap) {
104 if (CurField->hasCapturedVLAType()) {
105 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000106 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000107 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000108 } else if (CurCap->capturesThis())
109 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000110 else if (CurCap->capturesVariableByCopy())
111 CapturedVars.push_back(
112 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
113 else {
114 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000115 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000116 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000117 }
118}
119
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000120static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
121 StringRef Name, LValue AddrLV,
122 bool isReferenceType = false) {
123 ASTContext &Ctx = CGF.getContext();
124
125 auto *CastedPtr = CGF.EmitScalarConversion(
126 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
127 Ctx.getPointerType(DstType), SourceLocation());
128 auto TmpAddr =
129 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
130 .getAddress();
131
132 // If we are dealing with references we need to return the address of the
133 // reference instead of the reference of the value.
134 if (isReferenceType) {
135 QualType RefType = Ctx.getLValueReferenceType(DstType);
136 auto *RefVal = TmpAddr.getPointer();
137 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
138 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
139 CGF.EmitScalarInit(RefVal, TmpLVal);
140 }
141
142 return TmpAddr;
143}
144
Alexey Bataev2377fe92015-09-10 08:12:02 +0000145llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000146CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000147 assert(
148 CapturedStmtInfo &&
149 "CapturedStmtInfo should be set when generating the captured function");
150 const CapturedDecl *CD = S.getCapturedDecl();
151 const RecordDecl *RD = S.getCapturedRecordDecl();
152 assert(CD->hasBody() && "missing CapturedDecl body");
153
154 // Build the argument list.
155 ASTContext &Ctx = CGM.getContext();
156 FunctionArgList Args;
157 Args.append(CD->param_begin(),
158 std::next(CD->param_begin(), CD->getContextParamPosition()));
159 auto I = S.captures().begin();
160 for (auto *FD : RD->fields()) {
161 QualType ArgType = FD->getType();
162 IdentifierInfo *II = nullptr;
163 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000164
165 // If this is a capture by copy and the type is not a pointer, the outlined
166 // function argument type should be uintptr and the value properly casted to
167 // uintptr. This is necessary given that the runtime library is only able to
168 // deal with pointers. We can pass in the same way the VLA type sizes to the
169 // outlined function.
170 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
171 I->capturesVariableArrayType())
172 ArgType = Ctx.getUIntPtrType();
173
174 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000175 CapVar = I->getCapturedVar();
176 II = CapVar->getIdentifier();
177 } else if (I->capturesThis())
178 II = &getContext().Idents.get("this");
179 else {
180 assert(I->capturesVariableArrayType());
181 II = &getContext().Idents.get("vla");
182 }
183 if (ArgType->isVariablyModifiedType())
184 ArgType = getContext().getVariableArrayDecayedType(ArgType);
185 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
186 FD->getLocation(), II, ArgType));
187 ++I;
188 }
189 Args.append(
190 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
191 CD->param_end());
192
193 // Create the function declaration.
194 FunctionType::ExtInfo ExtInfo;
195 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000196 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000197 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
198
199 llvm::Function *F = llvm::Function::Create(
200 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
201 CapturedStmtInfo->getHelperName(), &CGM.getModule());
202 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
203 if (CD->isNothrow())
204 F->addFnAttr(llvm::Attribute::NoUnwind);
205
206 // Generate the function.
207 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
208 CD->getBody()->getLocStart());
209 unsigned Cnt = CD->getContextParamPosition();
210 I = S.captures().begin();
211 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000212 // If we are capturing a pointer by copy we don't need to do anything, just
213 // use the value that we get from the arguments.
214 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
215 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000216 ++Cnt;
217 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000218 continue;
219 }
220
Alexey Bataev2377fe92015-09-10 08:12:02 +0000221 LValue ArgLVal =
222 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
223 AlignmentSource::Decl);
224 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225 LValue CastedArgLVal =
226 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
227 Args[Cnt]->getName(), ArgLVal),
228 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000229 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000230 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000231 auto VAT = FD->getCapturedVLAType();
232 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
233 } else if (I->capturesVariable()) {
234 auto *Var = I->getCapturedVar();
235 QualType VarTy = Var->getType();
236 Address ArgAddr = ArgLVal.getAddress();
237 if (!VarTy->isReferenceType()) {
238 ArgAddr = EmitLoadOfReference(
239 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
240 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000241 setAddrOfLocalVar(
242 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000243 } else if (I->capturesVariableByCopy()) {
244 assert(!FD->getType()->isAnyPointerType() &&
245 "Not expecting a captured pointer.");
246 auto *Var = I->getCapturedVar();
247 QualType VarTy = Var->getType();
248 setAddrOfLocalVar(I->getCapturedVar(),
249 castValueFromUintptr(*this, FD->getType(),
250 Args[Cnt]->getName(), ArgLVal,
251 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000252 } else {
253 // If 'this' is captured, load it into CXXThisValue.
254 assert(I->capturesThis());
255 CXXThisValue =
256 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
257 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000258 ++Cnt;
259 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000260 }
261
Serge Pavlov3a561452015-12-06 14:32:39 +0000262 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000263 CapturedStmtInfo->EmitBody(*this, CD->getBody());
264 FinishFunction(CD->getBodyRBrace());
265
266 return F;
267}
268
Alexey Bataev9959db52014-05-06 10:08:46 +0000269//===----------------------------------------------------------------------===//
270// OpenMP Directive Emission
271//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000272void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000273 Address DestAddr, Address SrcAddr, QualType OriginalType,
274 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 // Perform element-by-element initialization.
276 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000277
278 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000279 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000280 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
281 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
282
283 auto SrcBegin = SrcAddr.getPointer();
284 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000285 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000286 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
287 // The basic structure here is a while-do loop.
288 auto BodyBB = createBasicBlock("omp.arraycpy.body");
289 auto DoneBB = createBasicBlock("omp.arraycpy.done");
290 auto IsEmpty =
291 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
292 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000293
Alexey Bataev420d45b2015-04-14 05:11:24 +0000294 // Enter the loop body, making that address the current address.
295 auto EntryBB = Builder.GetInsertBlock();
296 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000297
298 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
299
300 llvm::PHINode *SrcElementPHI =
301 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
302 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
303 Address SrcElementCurrent =
304 Address(SrcElementPHI,
305 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
306
307 llvm::PHINode *DestElementPHI =
308 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
309 DestElementPHI->addIncoming(DestBegin, EntryBB);
310 Address DestElementCurrent =
311 Address(DestElementPHI,
312 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000313
Alexey Bataev420d45b2015-04-14 05:11:24 +0000314 // Emit copy.
315 CopyGen(DestElementCurrent, SrcElementCurrent);
316
317 // Shift the address forward by one element.
318 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000319 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000320 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000321 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000322 // Check whether we've reached the end.
323 auto Done =
324 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
325 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000326 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
327 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000328
329 // Done.
330 EmitBlock(DoneBB, /*IsFinished=*/true);
331}
332
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000333/// Check if the combiner is a call to UDR combiner and if it is so return the
334/// UDR decl used for reduction.
335static const OMPDeclareReductionDecl *
336getReductionInit(const Expr *ReductionOp) {
337 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
338 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
339 if (auto *DRE =
340 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
341 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
342 return DRD;
343 return nullptr;
344}
345
346static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
347 const OMPDeclareReductionDecl *DRD,
348 const Expr *InitOp,
349 Address Private, Address Original,
350 QualType Ty) {
351 if (DRD->getInitializer()) {
352 std::pair<llvm::Function *, llvm::Function *> Reduction =
353 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
354 auto *CE = cast<CallExpr>(InitOp);
355 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
356 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
357 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
358 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
359 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
360 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
361 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
362 [=]() -> Address { return Private; });
363 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
364 [=]() -> Address { return Original; });
365 (void)PrivateScope.Privatize();
366 RValue Func = RValue::get(Reduction.second);
367 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
368 CGF.EmitIgnoredExpr(InitOp);
369 } else {
370 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
371 auto *GV = new llvm::GlobalVariable(
372 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
373 llvm::GlobalValue::PrivateLinkage, Init, ".init");
374 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
375 RValue InitRVal;
376 switch (CGF.getEvaluationKind(Ty)) {
377 case TEK_Scalar:
378 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
379 break;
380 case TEK_Complex:
381 InitRVal =
382 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
383 break;
384 case TEK_Aggregate:
385 InitRVal = RValue::getAggregate(LV.getAddress());
386 break;
387 }
388 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
389 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
390 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
391 /*IsInitializer=*/false);
392 }
393}
394
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000395/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000396/// \param DestAddr Address of the array.
397/// \param Type Type of array.
398/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000399/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000400static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000401 QualType Type, const Expr *Init,
402 Address SrcAddr = Address::invalid()) {
403 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000404 // Perform element-by-element initialization.
405 QualType ElementTy;
406
407 // Drill down to the base element type on both arrays.
408 auto ArrayTy = Type->getAsArrayTypeUnsafe();
409 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
410 DestAddr =
411 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000412 if (DRD)
413 SrcAddr =
414 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000415
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000416 llvm::Value *SrcBegin = nullptr;
417 if (DRD)
418 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000419 auto DestBegin = DestAddr.getPointer();
420 // Cast from pointer to array type to pointer to single element.
421 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
422 // The basic structure here is a while-do loop.
423 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
424 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
425 auto IsEmpty =
426 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
427 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
428
429 // Enter the loop body, making that address the current address.
430 auto EntryBB = CGF.Builder.GetInsertBlock();
431 CGF.EmitBlock(BodyBB);
432
433 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
434
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000435 llvm::PHINode *SrcElementPHI = nullptr;
436 Address SrcElementCurrent = Address::invalid();
437 if (DRD) {
438 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
439 "omp.arraycpy.srcElementPast");
440 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
441 SrcElementCurrent =
442 Address(SrcElementPHI,
443 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
444 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000445 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
446 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
447 DestElementPHI->addIncoming(DestBegin, EntryBB);
448 Address DestElementCurrent =
449 Address(DestElementPHI,
450 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
451
452 // Emit copy.
453 {
454 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000455 if (DRD) {
456 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
457 SrcElementCurrent, ElementTy);
458 } else
459 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
460 /*IsInitializer=*/false);
461 }
462
463 if (DRD) {
464 // Shift the address forward by one element.
465 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
466 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
467 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000468 }
469
470 // Shift the address forward by one element.
471 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
472 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
473 // Check whether we've reached the end.
474 auto Done =
475 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
476 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
477 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
478
479 // Done.
480 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
481}
482
John McCall7f416cc2015-09-08 08:05:57 +0000483void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
484 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000485 const VarDecl *SrcVD, const Expr *Copy) {
486 if (OriginalType->isArrayType()) {
487 auto *BO = dyn_cast<BinaryOperator>(Copy);
488 if (BO && BO->getOpcode() == BO_Assign) {
489 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000490 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000491 } else {
492 // For arrays with complex element types perform element by element
493 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000494 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000495 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000496 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000497 // Working with the single array element, so have to remap
498 // destination and source variables to corresponding array
499 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000500 CodeGenFunction::OMPPrivateScope Remap(*this);
501 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000502 return DestElement;
503 });
504 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000505 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000506 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000507 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000508 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000509 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000510 } else {
511 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000512 CodeGenFunction::OMPPrivateScope Remap(*this);
513 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
514 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000515 (void)Remap.Privatize();
516 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000517 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000518 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000519}
520
Alexey Bataev69c62a92015-04-15 04:52:20 +0000521bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
522 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000523 if (!HaveInsertPoint())
524 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000525 bool FirstprivateIsLastprivate = false;
526 llvm::DenseSet<const VarDecl *> Lastprivates;
527 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
528 for (const auto *D : C->varlists())
529 Lastprivates.insert(
530 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
531 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000532 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000533 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000534 auto IRef = C->varlist_begin();
535 auto InitsRef = C->inits().begin();
536 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000537 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000538 FirstprivateIsLastprivate =
539 FirstprivateIsLastprivate ||
540 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
541 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000542 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
543 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
544 bool IsRegistered;
545 DeclRefExpr DRE(
546 const_cast<VarDecl *>(OrigVD),
547 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
548 OrigVD) != nullptr,
549 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000550 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000551 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000552 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000553 // Emit VarDecl with copy init for arrays.
554 // Get the address of the original variable captured in current
555 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000556 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000557 auto Emission = EmitAutoVarAlloca(*VD);
558 auto *Init = VD->getInit();
559 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
560 // Perform simple memcpy.
561 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000562 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000563 } else {
564 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000565 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000566 [this, VDInit, Init](Address DestElement,
567 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000568 // Clean up any temporaries needed by the initialization.
569 RunCleanupsScope InitScope(*this);
570 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000571 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000572 EmitAnyExprToMem(Init, DestElement,
573 Init->getType().getQualifiers(),
574 /*IsInitializer*/ false);
575 LocalDeclMap.erase(VDInit);
576 });
577 }
578 EmitAutoVarCleanups(Emission);
579 return Emission.getAllocatedAddress();
580 });
581 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000582 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000583 // Emit private VarDecl with copy init.
584 // Remap temp VDInit variable to the address of the original
585 // variable
586 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000587 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000588 EmitDecl(*VD);
589 LocalDeclMap.erase(VDInit);
590 return GetAddrOfLocalVar(VD);
591 });
592 }
593 assert(IsRegistered &&
594 "firstprivate var already registered as private");
595 // Silence the warning about unused variable.
596 (void)IsRegistered;
597 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000598 ++IRef;
599 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000600 }
601 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000602 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000603}
604
Alexey Bataev03b340a2014-10-21 03:16:40 +0000605void CodeGenFunction::EmitOMPPrivateClause(
606 const OMPExecutableDirective &D,
607 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000608 if (!HaveInsertPoint())
609 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000610 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000611 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000612 auto IRef = C->varlist_begin();
613 for (auto IInit : C->private_copies()) {
614 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000615 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
616 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
617 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000618 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000619 // Emit private VarDecl with copy init.
620 EmitDecl(*VD);
621 return GetAddrOfLocalVar(VD);
622 });
623 assert(IsRegistered && "private var already registered as private");
624 // Silence the warning about unused variable.
625 (void)IsRegistered;
626 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000627 ++IRef;
628 }
629 }
630}
631
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000632bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000633 if (!HaveInsertPoint())
634 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000635 // threadprivate_var1 = master_threadprivate_var1;
636 // operator=(threadprivate_var2, master_threadprivate_var2);
637 // ...
638 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000639 llvm::DenseSet<const VarDecl *> CopiedVars;
640 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000641 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000642 auto IRef = C->varlist_begin();
643 auto ISrcRef = C->source_exprs().begin();
644 auto IDestRef = C->destination_exprs().begin();
645 for (auto *AssignOp : C->assignment_ops()) {
646 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000647 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000648 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000649 // Get the address of the master variable. If we are emitting code with
650 // TLS support, the address is passed from the master as field in the
651 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000652 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000653 if (getLangOpts().OpenMPUseTLS &&
654 getContext().getTargetInfo().isTLSSupported()) {
655 assert(CapturedStmtInfo->lookup(VD) &&
656 "Copyin threadprivates should have been captured!");
657 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
658 VK_LValue, (*IRef)->getExprLoc());
659 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000660 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000661 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000662 MasterAddr =
663 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
664 : CGM.GetAddrOfGlobal(VD),
665 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000666 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000667 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000668 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000669 if (CopiedVars.size() == 1) {
670 // At first check if current thread is a master thread. If it is, no
671 // need to copy data.
672 CopyBegin = createBasicBlock("copyin.not.master");
673 CopyEnd = createBasicBlock("copyin.not.master.end");
674 Builder.CreateCondBr(
675 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000676 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
677 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000678 CopyBegin, CopyEnd);
679 EmitBlock(CopyBegin);
680 }
681 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
682 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000683 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000684 }
685 ++IRef;
686 ++ISrcRef;
687 ++IDestRef;
688 }
689 }
690 if (CopyEnd) {
691 // Exit out of copying procedure for non-master thread.
692 EmitBlock(CopyEnd, /*IsFinished=*/true);
693 return true;
694 }
695 return false;
696}
697
Alexey Bataev38e89532015-04-16 04:54:05 +0000698bool CodeGenFunction::EmitOMPLastprivateClauseInit(
699 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000700 if (!HaveInsertPoint())
701 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000702 bool HasAtLeastOneLastprivate = false;
703 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000704 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000705 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000706 auto IRef = C->varlist_begin();
707 auto IDestRef = C->destination_exprs().begin();
708 for (auto *IInit : C->private_copies()) {
709 // Keep the address of the original variable for future update at the end
710 // of the loop.
711 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
712 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
713 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000714 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000715 DeclRefExpr DRE(
716 const_cast<VarDecl *>(OrigVD),
717 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
718 OrigVD) != nullptr,
719 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
720 return EmitLValue(&DRE).getAddress();
721 });
722 // Check if the variable is also a firstprivate: in this case IInit is
723 // not generated. Initialization of this variable will happen in codegen
724 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000725 if (IInit) {
726 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
727 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000728 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000729 // Emit private VarDecl with copy init.
730 EmitDecl(*VD);
731 return GetAddrOfLocalVar(VD);
732 });
733 assert(IsRegistered &&
734 "lastprivate var already registered as private");
735 (void)IsRegistered;
736 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000737 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000738 ++IRef;
739 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000740 }
741 }
742 return HasAtLeastOneLastprivate;
743}
744
745void CodeGenFunction::EmitOMPLastprivateClauseFinal(
746 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000747 if (!HaveInsertPoint())
748 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000749 // Emit following code:
750 // if (<IsLastIterCond>) {
751 // orig_var1 = private_orig_var1;
752 // ...
753 // orig_varn = private_orig_varn;
754 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000755 llvm::BasicBlock *ThenBB = nullptr;
756 llvm::BasicBlock *DoneBB = nullptr;
757 if (IsLastIterCond) {
758 ThenBB = createBasicBlock(".omp.lastprivate.then");
759 DoneBB = createBasicBlock(".omp.lastprivate.done");
760 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
761 EmitBlock(ThenBB);
762 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000763 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000764 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000765 auto IC = LoopDirective->counters().begin();
766 for (auto F : LoopDirective->finals()) {
767 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
768 LoopCountersAndUpdates[D] = F;
769 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000770 }
771 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000772 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
773 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
774 auto IRef = C->varlist_begin();
775 auto ISrcRef = C->source_exprs().begin();
776 auto IDestRef = C->destination_exprs().begin();
777 for (auto *AssignOp : C->assignment_ops()) {
778 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
779 QualType Type = PrivateVD->getType();
780 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
781 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
782 // If lastprivate variable is a loop control variable for loop-based
783 // directive, update its value before copyin back to original
784 // variable.
785 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
786 EmitIgnoredExpr(UpExpr);
787 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
788 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
789 // Get the address of the original variable.
790 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
791 // Get the address of the private variable.
792 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
793 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
794 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000795 Address(Builder.CreateLoad(PrivateAddr),
796 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000797 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000798 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000799 ++IRef;
800 ++ISrcRef;
801 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000802 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000803 if (auto *PostUpdate = C->getPostUpdateExpr())
804 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000805 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000806 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000807 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000808}
809
Alexey Bataev31300ed2016-02-04 11:27:03 +0000810static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
811 LValue BaseLV, llvm::Value *Addr) {
812 Address Tmp = Address::invalid();
813 Address TopTmp = Address::invalid();
814 Address MostTopTmp = Address::invalid();
815 BaseTy = BaseTy.getNonReferenceType();
816 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
817 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
818 Tmp = CGF.CreateMemTemp(BaseTy);
819 if (TopTmp.isValid())
820 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
821 else
822 MostTopTmp = Tmp;
823 TopTmp = Tmp;
824 BaseTy = BaseTy->getPointeeType();
825 }
826 llvm::Type *Ty = BaseLV.getPointer()->getType();
827 if (Tmp.isValid())
828 Ty = Tmp.getElementType();
829 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
830 if (Tmp.isValid()) {
831 CGF.Builder.CreateStore(Addr, Tmp);
832 return MostTopTmp;
833 }
834 return Address(Addr, BaseLV.getAlignment());
835}
836
837static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
838 LValue BaseLV) {
839 BaseTy = BaseTy.getNonReferenceType();
840 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
841 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
842 if (auto *PtrTy = BaseTy->getAs<PointerType>())
843 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
844 else {
845 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
846 BaseTy->castAs<ReferenceType>());
847 }
848 BaseTy = BaseTy->getPointeeType();
849 }
850 return CGF.MakeAddrLValue(
851 Address(
852 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
853 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
854 BaseLV.getAlignment()),
855 BaseLV.getType(), BaseLV.getAlignmentSource());
856}
857
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000858void CodeGenFunction::EmitOMPReductionClauseInit(
859 const OMPExecutableDirective &D,
860 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000861 if (!HaveInsertPoint())
862 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000863 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000864 auto ILHS = C->lhs_exprs().begin();
865 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000866 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000867 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000868 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000869 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000870 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
871 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000872 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000873 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
874 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
875 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
876 Base = TempOASE->getBase()->IgnoreParenImpCasts();
877 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
878 Base = TempASE->getBase()->IgnoreParenImpCasts();
879 auto *DE = cast<DeclRefExpr>(Base);
880 auto *OrigVD = cast<VarDecl>(DE->getDecl());
881 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
882 auto OASELValueUB =
883 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
884 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000885 LValue BaseLValue =
886 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
887 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000888 // Store the address of the original variable associated with the LHS
889 // implicit variable.
890 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
891 return OASELValueLB.getAddress();
892 });
893 // Emit reduction copy.
894 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000895 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000896 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000897 // Emit VarDecl with copy init for arrays.
898 // Get the address of the original variable captured in current
899 // captured region.
900 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
901 OASELValueLB.getPointer());
902 Size = Builder.CreateNUWAdd(
903 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
904 CodeGenFunction::OpaqueValueMapping OpaqueMap(
905 *this, cast<OpaqueValueExpr>(
906 getContext()
907 .getAsVariableArrayType(PrivateVD->getType())
908 ->getSizeExpr()),
909 RValue::get(Size));
910 EmitVariablyModifiedType(PrivateVD->getType());
911 auto Emission = EmitAutoVarAlloca(*PrivateVD);
912 auto Addr = Emission.getAllocatedAddress();
913 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000914 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
915 DRD ? *IRed : Init,
916 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000917 EmitAutoVarCleanups(Emission);
918 // Emit private VarDecl with reduction init.
919 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
920 OASELValueLB.getPointer());
921 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000922 return castToBase(*this, OrigVD->getType(),
923 OASELValueLB.getType(), OriginalBaseLValue,
924 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000925 });
926 assert(IsRegistered && "private var already registered as private");
927 // Silence the warning about unused variable.
928 (void)IsRegistered;
929 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
930 return GetAddrOfLocalVar(PrivateVD);
931 });
932 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
933 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
934 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
935 Base = TempASE->getBase()->IgnoreParenImpCasts();
936 auto *DE = cast<DeclRefExpr>(Base);
937 auto *OrigVD = cast<VarDecl>(DE->getDecl());
938 auto ASELValue = EmitLValue(ASE);
939 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000940 LValue BaseLValue = loadToBegin(
941 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000942 // Store the address of the original variable associated with the LHS
943 // implicit variable.
944 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
945 return ASELValue.getAddress();
946 });
947 // Emit reduction copy.
948 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000949 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000950 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000951 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000952 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
953 auto Addr = Emission.getAllocatedAddress();
954 if (DRD) {
955 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
956 ASELValue.getAddress(),
957 ASELValue.getType());
958 } else
959 EmitAutoVarInit(Emission);
960 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000961 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
962 ASELValue.getPointer());
963 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000964 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
965 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000966 });
967 assert(IsRegistered && "private var already registered as private");
968 // Silence the warning about unused variable.
969 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000970 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
971 return Builder.CreateElementBitCast(
972 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
973 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000974 });
975 } else {
976 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000977 QualType Type = PrivateVD->getType();
978 if (getContext().getAsArrayType(Type)) {
979 // Store the address of the original variable associated with the LHS
980 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000981 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
982 CapturedStmtInfo->lookup(OrigVD) != nullptr,
983 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000984 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000985 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +0000986 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000987 OriginalAddr = Builder.CreateElementBitCast(
988 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
989 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000990 });
991 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
992 if (Type->isVariablyModifiedType()) {
993 CodeGenFunction::OpaqueValueMapping OpaqueMap(
994 *this, cast<OpaqueValueExpr>(
995 getContext()
996 .getAsVariableArrayType(PrivateVD->getType())
997 ->getSizeExpr()),
998 RValue::get(
999 getTypeSize(OrigVD->getType().getNonReferenceType())));
1000 EmitVariablyModifiedType(Type);
1001 }
1002 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1003 auto Addr = Emission.getAllocatedAddress();
1004 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001005 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1006 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001007 EmitAutoVarCleanups(Emission);
1008 return Emission.getAllocatedAddress();
1009 });
1010 assert(IsRegistered && "private var already registered as private");
1011 // Silence the warning about unused variable.
1012 (void)IsRegistered;
1013 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1014 return Builder.CreateElementBitCast(
1015 GetAddrOfLocalVar(PrivateVD),
1016 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1017 });
1018 } else {
1019 // Store the address of the original variable associated with the LHS
1020 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001021 Address OriginalAddr = Address::invalid();
1022 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1023 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001024 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1025 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1026 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001027 OriginalAddr = EmitLValue(&DRE).getAddress();
1028 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001029 });
1030 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001031 bool IsRegistered = PrivateScope.addPrivate(
1032 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001033 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001034 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1035 auto Addr = Emission.getAllocatedAddress();
1036 if (DRD) {
1037 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1038 OriginalAddr,
1039 PrivateVD->getType());
1040 } else
1041 EmitAutoVarInit(Emission);
1042 EmitAutoVarCleanups(Emission);
1043 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001044 });
1045 assert(IsRegistered && "private var already registered as private");
1046 // Silence the warning about unused variable.
1047 (void)IsRegistered;
1048 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1049 return GetAddrOfLocalVar(PrivateVD);
1050 });
1051 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001052 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001053 ++ILHS;
1054 ++IRHS;
1055 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001056 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001057 }
1058 }
1059}
1060
1061void CodeGenFunction::EmitOMPReductionClauseFinal(
1062 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001063 if (!HaveInsertPoint())
1064 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001065 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001066 llvm::SmallVector<const Expr *, 8> LHSExprs;
1067 llvm::SmallVector<const Expr *, 8> RHSExprs;
1068 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001069 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001070 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001071 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001072 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001073 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1074 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1075 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1076 }
1077 if (HasAtLeastOneReduction) {
1078 // Emit nowait reduction if nowait clause is present or directive is a
1079 // parallel directive (it always has implicit barrier).
1080 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001081 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001082 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001083 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1084 D.getDirectiveKind() == OMPD_simd,
1085 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001086 }
1087}
1088
Alexey Bataev61205072016-03-02 04:57:40 +00001089static void emitPostUpdateForReductionClause(
1090 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1091 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1092 if (!CGF.HaveInsertPoint())
1093 return;
1094 llvm::BasicBlock *DoneBB = nullptr;
1095 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1096 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1097 if (!DoneBB) {
1098 if (auto *Cond = CondGen(CGF)) {
1099 // If the first post-update expression is found, emit conditional
1100 // block if it was requested.
1101 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1102 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1103 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1104 CGF.EmitBlock(ThenBB);
1105 }
1106 }
1107 CGF.EmitIgnoredExpr(PostUpdate);
1108 }
1109 }
1110 if (DoneBB)
1111 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1112}
1113
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001114static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1115 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001116 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001117 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001118 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001119 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1120 emitParallelOrTeamsOutlinedFunction(S,
1121 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001122 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001123 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001124 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1125 /*IgnoreResultAssign*/ true);
1126 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1127 CGF, NumThreads, NumThreadsClause->getLocStart());
1128 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001129 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001130 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001131 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1132 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1133 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001134 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001135 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1136 if (C->getNameModifier() == OMPD_unknown ||
1137 C->getNameModifier() == OMPD_parallel) {
1138 IfCond = C->getCondition();
1139 break;
1140 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001141 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001142
1143 OMPLexicalScope Scope(CGF, S);
1144 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1145 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001146 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001147 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001148}
1149
1150void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001151 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001152 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001153 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001154 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001155 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1156 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001157 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001158 // propagation master's thread values of threadprivate variables to local
1159 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001160 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1161 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1162 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001163 }
1164 CGF.EmitOMPPrivateClause(S, PrivateScope);
1165 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1166 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001168 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001169 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001170 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001171 emitPostUpdateForReductionClause(
1172 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001173}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001174
Alexey Bataev0f34da12015-07-02 04:17:07 +00001175void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1176 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001177 RunCleanupsScope BodyScope(*this);
1178 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001179 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001180 EmitIgnoredExpr(I);
1181 }
Alexander Musman3276a272015-03-21 10:12:56 +00001182 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001183 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001184 for (auto U : C->updates()) {
1185 EmitIgnoredExpr(U);
1186 }
1187 }
1188
Alexander Musmana5f070a2014-10-01 06:03:56 +00001189 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001190 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001191 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001192 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001193 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001194 // The end (updates/cleanups).
1195 EmitBlock(Continue.getBlock());
1196 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001197}
1198
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001199void CodeGenFunction::EmitOMPInnerLoop(
1200 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1201 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001202 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1203 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001204 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001205
1206 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001207 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001208 EmitBlock(CondBlock);
1209 LoopStack.push(CondBlock);
1210
1211 // If there are any cleanups between here and the loop-exit scope,
1212 // create a block to stage a loop exit along.
1213 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001214 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001215 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001216
Alexander Musmand196ef22014-10-07 08:57:09 +00001217 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001218
Alexey Bataev2df54a02015-03-12 08:53:29 +00001219 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001220 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001221 if (ExitBlock != LoopExit.getBlock()) {
1222 EmitBlock(ExitBlock);
1223 EmitBranchThroughCleanup(LoopExit);
1224 }
1225
1226 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001227 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001228
1229 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001230 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001231 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1232
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001233 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001234
1235 // Emit "IV = IV + 1" and a back-edge to the condition block.
1236 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001237 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001238 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001239 BreakContinueStack.pop_back();
1240 EmitBranch(CondBlock);
1241 LoopStack.pop();
1242 // Emit the fall-through block.
1243 EmitBlock(LoopExit.getBlock());
1244}
1245
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001246void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001247 if (!HaveInsertPoint())
1248 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001249 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001250 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001251 for (auto Init : C->inits()) {
1252 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001253 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1254 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1255 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1256 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1257 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1258 VD->getInit()->getType(), VK_LValue,
1259 VD->getInit()->getExprLoc());
1260 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1261 VD->getType()),
1262 /*capturedByInit=*/false);
1263 EmitAutoVarCleanups(Emission);
1264 } else
1265 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001266 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001267 // Emit the linear steps for the linear clauses.
1268 // If a step is not constant, it is pre-calculated before the loop.
1269 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1270 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001271 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001272 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001273 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001274 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001275 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001276}
1277
Alexey Bataevef549a82016-03-09 09:49:09 +00001278static void emitLinearClauseFinal(
1279 CodeGenFunction &CGF, const OMPLoopDirective &D,
1280 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001281 if (!CGF.HaveInsertPoint())
1282 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001283 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001284 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001285 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001286 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001287 for (auto F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001288 if (!DoneBB) {
1289 if (auto *Cond = CondGen(CGF)) {
1290 // If the first post-update expression is found, emit conditional
1291 // block if it was requested.
1292 auto *ThenBB = CGF.createBasicBlock(".omp.linear.pu");
1293 DoneBB = CGF.createBasicBlock(".omp.linear.pu.done");
1294 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1295 CGF.EmitBlock(ThenBB);
1296 }
1297 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001298 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1299 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001300 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001301 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001302 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001303 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001304 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001305 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001306 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001307 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001308 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001309 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001310 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataevef549a82016-03-09 09:49:09 +00001311 CGF.EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001312 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001313 if (DoneBB)
1314 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001315}
1316
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001317static void emitAlignedClause(CodeGenFunction &CGF,
1318 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001319 if (!CGF.HaveInsertPoint())
1320 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001321 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001322 unsigned ClauseAlignment = 0;
1323 if (auto AlignmentExpr = Clause->getAlignment()) {
1324 auto AlignmentCI =
1325 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1326 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001327 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001328 for (auto E : Clause->varlists()) {
1329 unsigned Alignment = ClauseAlignment;
1330 if (Alignment == 0) {
1331 // OpenMP [2.8.1, Description]
1332 // If no optional parameter is specified, implementation-defined default
1333 // alignments for SIMD instructions on the target platforms are assumed.
1334 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001335 CGF.getContext()
1336 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1337 E->getType()->getPointeeType()))
1338 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001339 }
1340 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1341 "alignment is not power of 2");
1342 if (Alignment != 0) {
1343 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1344 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1345 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001346 }
1347 }
1348}
1349
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001350static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001351 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001352 ArrayRef<Expr *> Counters,
1353 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001354 if (!CGF.HaveInsertPoint())
1355 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001356 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001357 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001358 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1359 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001360 Address Addr = Address::invalid();
1361 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001362 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001363 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001364 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001365 Addr = VarEmission.getAllocatedAddress();
1366 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001367 });
John McCall7f416cc2015-09-08 08:05:57 +00001368 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001369 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001370 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001371}
1372
Alexey Bataev62dbb972015-04-22 11:59:37 +00001373static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1374 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1375 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001376 if (!CGF.HaveInsertPoint())
1377 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001378 {
1379 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001380 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1381 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001382 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001383 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001384 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001385 CGF.EmitIgnoredExpr(I);
1386 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001387 }
1388 // Check that loop is executed at least one time.
1389 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1390}
1391
Alexander Musman3276a272015-03-21 10:12:56 +00001392static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001393emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001394 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001395 if (!CGF.HaveInsertPoint())
1396 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001397 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001398 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001399 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001400 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1401 auto *PrivateVD =
1402 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001403 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001404 // Emit private VarDecl with copy init.
1405 CGF.EmitVarDecl(*PrivateVD);
1406 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001407 });
1408 assert(IsRegistered && "linear var already registered as private");
1409 // Silence the warning about unused variable.
1410 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001411 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001412 }
1413 }
1414}
1415
Alexey Bataev45bfad52015-08-21 12:19:04 +00001416static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001417 const OMPExecutableDirective &D,
1418 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001419 if (!CGF.HaveInsertPoint())
1420 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001421 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001422 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1423 /*ignoreResult=*/true);
1424 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1425 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1426 // In presence of finite 'safelen', it may be unsafe to mark all
1427 // the memory instructions parallel, because loop-carried
1428 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001429 if (!IsMonotonic)
1430 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001431 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001432 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1433 /*ignoreResult=*/true);
1434 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001435 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001436 // In presence of finite 'safelen', it may be unsafe to mark all
1437 // the memory instructions parallel, because loop-carried
1438 // dependences of 'safelen' iterations are possible.
1439 CGF.LoopStack.setParallel(false);
1440 }
1441}
1442
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001443void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1444 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001445 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001446 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001447 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001448 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001449}
1450
Alexey Bataevef549a82016-03-09 09:49:09 +00001451void CodeGenFunction::EmitOMPSimdFinal(
1452 const OMPLoopDirective &D,
1453 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001454 if (!HaveInsertPoint())
1455 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001456 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001457 auto IC = D.counters().begin();
1458 for (auto F : D.finals()) {
1459 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001460 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001461 if (!DoneBB) {
1462 if (auto *Cond = CondGen(*this)) {
1463 // If the first post-update expression is found, emit conditional
1464 // block if it was requested.
1465 auto *ThenBB = createBasicBlock(".omp.final.then");
1466 DoneBB = createBasicBlock(".omp.final.done");
1467 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1468 EmitBlock(ThenBB);
1469 }
1470 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001471 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1472 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1473 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001474 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001475 OMPPrivateScope VarScope(*this);
1476 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001477 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001478 (void)VarScope.Privatize();
1479 EmitIgnoredExpr(F);
1480 }
1481 ++IC;
1482 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001483 if (DoneBB)
1484 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001485}
1486
Alexander Musman515ad8c2014-05-22 08:54:05 +00001487void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001488 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001489 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001490 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001491 // for (IV in 0..LastIteration) BODY;
1492 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001493 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001494 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001495
Alexey Bataev62dbb972015-04-22 11:59:37 +00001496 // Emit: if (PreCond) - begin.
1497 // If the condition constant folds and can be elided, avoid emitting the
1498 // whole loop.
1499 bool CondConstant;
1500 llvm::BasicBlock *ContBlock = nullptr;
1501 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1502 if (!CondConstant)
1503 return;
1504 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001505 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1506 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001507 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1508 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001509 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001510 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001511 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001512
1513 // Emit the loop iteration variable.
1514 const Expr *IVExpr = S.getIterationVariable();
1515 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1516 CGF.EmitVarDecl(*IVDecl);
1517 CGF.EmitIgnoredExpr(S.getInit());
1518
1519 // Emit the iterations count variable.
1520 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001521 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001522 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1523 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1524 // Emit calculation of the iterations count.
1525 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001526 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001527
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001528 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001529
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001530 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001531 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001532 {
1533 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001534 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1535 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001536 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001537 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001538 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001539 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001540 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001541 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1542 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001543 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001544 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001545 CGF.EmitStopPoint(&S);
1546 },
1547 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001548 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001549 if (HasLastprivateClause)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001550 CGF.EmitOMPLastprivateClauseFinal(S);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001551 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001552 emitPostUpdateForReductionClause(
1553 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001554 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001555 CGF.EmitOMPSimdFinal(
1556 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1557 emitLinearClauseFinal(
1558 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001559 // Emit: if (PreCond) - end.
1560 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001561 CGF.EmitBranch(ContBlock);
1562 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001563 }
1564 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001565 OMPLexicalScope Scope(*this, S);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001566 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001567}
1568
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001569void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001570 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1571 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001572 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001573
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001574 const Expr *IVExpr = S.getIterationVariable();
1575 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1576 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1577
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001578 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1579
1580 // Start the loop with a block that tests the condition.
1581 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1582 EmitBlock(CondBlock);
1583 LoopStack.push(CondBlock);
1584
1585 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001586 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001587 // UB = min(UB, GlobalUB)
1588 EmitIgnoredExpr(S.getEnsureUpperBound());
1589 // IV = LB
1590 EmitIgnoredExpr(S.getInit());
1591 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001592 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001593 } else {
1594 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1595 IL, LB, UB, ST);
1596 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001597
1598 // If there are any cleanups between here and the loop-exit scope,
1599 // create a block to stage a loop exit along.
1600 auto ExitBlock = LoopExit.getBlock();
1601 if (LoopScope.requiresCleanups())
1602 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1603
1604 auto LoopBody = createBasicBlock("omp.dispatch.body");
1605 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1606 if (ExitBlock != LoopExit.getBlock()) {
1607 EmitBlock(ExitBlock);
1608 EmitBranchThroughCleanup(LoopExit);
1609 }
1610 EmitBlock(LoopBody);
1611
Alexander Musman92bdaab2015-03-12 13:37:50 +00001612 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1613 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001614 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001615 EmitIgnoredExpr(S.getInit());
1616
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001617 // Create a block for the increment.
1618 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1619 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1620
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001621 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1622 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001623 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1624 LoopStack.setParallel(!IsMonotonic);
1625 else
1626 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001627
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001628 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001629 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1630 [&S, LoopExit](CodeGenFunction &CGF) {
1631 CGF.EmitOMPLoopBody(S, LoopExit);
1632 CGF.EmitStopPoint(&S);
1633 },
1634 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1635 if (Ordered) {
1636 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1637 CGF, Loc, IVSize, IVSigned);
1638 }
1639 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001640
1641 EmitBlock(Continue.getBlock());
1642 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001643 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001644 // Emit "LB = LB + Stride", "UB = UB + Stride".
1645 EmitIgnoredExpr(S.getNextLowerBound());
1646 EmitIgnoredExpr(S.getNextUpperBound());
1647 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001648
1649 EmitBranch(CondBlock);
1650 LoopStack.pop();
1651 // Emit the fall-through block.
1652 EmitBlock(LoopExit.getBlock());
1653
1654 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001655 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001656 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001657
1658}
1659
1660void CodeGenFunction::EmitOMPForOuterLoop(
1661 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1662 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1663 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1664 auto &RT = CGM.getOpenMPRuntime();
1665
1666 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1667 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1668
1669 assert((Ordered ||
1670 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1671 "static non-chunked schedule does not need outer loop");
1672
1673 // Emit outer loop.
1674 //
1675 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1676 // When schedule(dynamic,chunk_size) is specified, the iterations are
1677 // distributed to threads in the team in chunks as the threads request them.
1678 // Each thread executes a chunk of iterations, then requests another chunk,
1679 // until no chunks remain to be distributed. Each chunk contains chunk_size
1680 // iterations, except for the last chunk to be distributed, which may have
1681 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1682 //
1683 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1684 // to threads in the team in chunks as the executing threads request them.
1685 // Each thread executes a chunk of iterations, then requests another chunk,
1686 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1687 // each chunk is proportional to the number of unassigned iterations divided
1688 // by the number of threads in the team, decreasing to 1. For a chunk_size
1689 // with value k (greater than 1), the size of each chunk is determined in the
1690 // same way, with the restriction that the chunks do not contain fewer than k
1691 // iterations (except for the last chunk to be assigned, which may have fewer
1692 // than k iterations).
1693 //
1694 // When schedule(auto) is specified, the decision regarding scheduling is
1695 // delegated to the compiler and/or runtime system. The programmer gives the
1696 // implementation the freedom to choose any possible mapping of iterations to
1697 // threads in the team.
1698 //
1699 // When schedule(runtime) is specified, the decision regarding scheduling is
1700 // deferred until run time, and the schedule and chunk size are taken from the
1701 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1702 // implementation defined
1703 //
1704 // while(__kmpc_dispatch_next(&LB, &UB)) {
1705 // idx = LB;
1706 // while (idx <= UB) { BODY; ++idx;
1707 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1708 // } // inner loop
1709 // }
1710 //
1711 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1712 // When schedule(static, chunk_size) is specified, iterations are divided into
1713 // chunks of size chunk_size, and the chunks are assigned to the threads in
1714 // the team in a round-robin fashion in the order of the thread number.
1715 //
1716 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1717 // while (idx <= UB) { BODY; ++idx; } // inner loop
1718 // LB = LB + ST;
1719 // UB = UB + ST;
1720 // }
1721 //
1722
1723 const Expr *IVExpr = S.getIterationVariable();
1724 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1725 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1726
1727 if (DynamicOrOrdered) {
1728 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1729 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1730 IVSize, IVSigned, Ordered, UBVal, Chunk);
1731 } else {
1732 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1733 Ordered, IL, LB, UB, ST, Chunk);
1734 }
1735
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001736 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001737 ST, IL, Chunk);
1738}
1739
1740void CodeGenFunction::EmitOMPDistributeOuterLoop(
1741 OpenMPDistScheduleClauseKind ScheduleKind,
1742 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1743 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1744
1745 auto &RT = CGM.getOpenMPRuntime();
1746
1747 // Emit outer loop.
1748 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1749 // dynamic
1750 //
1751
1752 const Expr *IVExpr = S.getIterationVariable();
1753 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1754 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1755
1756 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1757 IVSize, IVSigned, /* Ordered = */ false,
1758 IL, LB, UB, ST, Chunk);
1759
1760 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1761 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001762}
1763
Alexander Musmanc6388682014-12-15 07:07:06 +00001764/// \brief Emit a helper variable and return corresponding lvalue.
1765static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1766 const DeclRefExpr *Helper) {
1767 auto VDecl = cast<VarDecl>(Helper->getDecl());
1768 CGF.EmitVarDecl(*VDecl);
1769 return CGF.EmitLValue(Helper);
1770}
1771
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001772namespace {
1773 struct ScheduleKindModifiersTy {
1774 OpenMPScheduleClauseKind Kind;
1775 OpenMPScheduleClauseModifier M1;
1776 OpenMPScheduleClauseModifier M2;
1777 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1778 OpenMPScheduleClauseModifier M1,
1779 OpenMPScheduleClauseModifier M2)
1780 : Kind(Kind), M1(M1), M2(M2) {}
1781 };
1782} // namespace
1783
Alexey Bataev38e89532015-04-16 04:54:05 +00001784bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001785 // Emit the loop iteration variable.
1786 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1787 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1788 EmitVarDecl(*IVDecl);
1789
1790 // Emit the iterations count variable.
1791 // If it is not a variable, Sema decided to calculate iterations count on each
1792 // iteration (e.g., it is foldable into a constant).
1793 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1794 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1795 // Emit calculation of the iterations count.
1796 EmitIgnoredExpr(S.getCalcLastIteration());
1797 }
1798
1799 auto &RT = CGM.getOpenMPRuntime();
1800
Alexey Bataev38e89532015-04-16 04:54:05 +00001801 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001802 // Check pre-condition.
1803 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001804 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001805 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001806 // If the condition constant folds and can be elided, avoid emitting the
1807 // whole loop.
1808 bool CondConstant;
1809 llvm::BasicBlock *ContBlock = nullptr;
1810 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1811 if (!CondConstant)
1812 return false;
1813 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001814 auto *ThenBlock = createBasicBlock("omp.precond.then");
1815 ContBlock = createBasicBlock("omp.precond.end");
1816 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001817 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001818 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001819 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001820 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001821
1822 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001823 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00001824 // Emit helper vars inits.
1825 LValue LB =
1826 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1827 LValue UB =
1828 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1829 LValue ST =
1830 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1831 LValue IL =
1832 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1833
Alexander Musmanc6388682014-12-15 07:07:06 +00001834 // Emit 'then' code.
1835 {
Alexander Musmanc6388682014-12-15 07:07:06 +00001836 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001837 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1838 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001839 // initialization of firstprivate variables and post-update of
1840 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001841 CGM.getOpenMPRuntime().emitBarrierCall(
1842 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1843 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001844 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001845 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001846 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001847 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001848 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1849 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001850 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001851 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001852
1853 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001854 llvm::Value *Chunk = nullptr;
1855 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1856 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1857 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1858 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1859 ScheduleKind = C->getScheduleKind();
1860 M1 = C->getFirstScheduleModifier();
1861 M2 = C->getSecondScheduleModifier();
1862 if (const auto *Ch = C->getChunkSize()) {
1863 Chunk = EmitScalarExpr(Ch);
1864 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1865 S.getIterationVariable()->getType(),
1866 S.getLocStart());
1867 }
1868 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001869 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1870 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001871 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001872 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1873 // If the static schedule kind is specified or if the ordered clause is
1874 // specified, and if no monotonic modifier is specified, the effect will
1875 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001876 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001877 /* Chunked */ Chunk != nullptr) &&
1878 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001879 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1880 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001881 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1882 // When no chunk_size is specified, the iteration space is divided into
1883 // chunks that are approximately equal in size, and at most one chunk is
1884 // distributed to each thread. Note that the size of the chunks is
1885 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001886 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1887 IVSize, IVSigned, Ordered,
1888 IL.getAddress(), LB.getAddress(),
1889 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001890 auto LoopExit =
1891 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001892 // UB = min(UB, GlobalUB);
1893 EmitIgnoredExpr(S.getEnsureUpperBound());
1894 // IV = LB;
1895 EmitIgnoredExpr(S.getInit());
1896 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001897 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1898 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001899 [&S, LoopExit](CodeGenFunction &CGF) {
1900 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001901 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001902 },
1903 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001904 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001905 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001906 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001907 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001908 const bool IsMonotonic = Ordered ||
1909 ScheduleKind == OMPC_SCHEDULE_static ||
1910 ScheduleKind == OMPC_SCHEDULE_unknown ||
1911 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1912 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001913 // Emit the outer loop, which requests its work chunk [LB..UB] from
1914 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001915 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001916 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1917 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001918 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001919 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001920 // Emit post-update of the reduction variables if IsLastIter != 0.
1921 emitPostUpdateForReductionClause(
1922 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1923 return CGF.Builder.CreateIsNotNull(
1924 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1925 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001926 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1927 if (HasLastprivateClause)
1928 EmitOMPLastprivateClauseFinal(
1929 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001930 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001931 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001932 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1933 return CGF.Builder.CreateIsNotNull(
1934 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1935 });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001936 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001937 emitLinearClauseFinal(*this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1938 return CGF.Builder.CreateIsNotNull(
1939 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1940 });
Alexander Musmanc6388682014-12-15 07:07:06 +00001941 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001942 if (ContBlock) {
1943 EmitBranch(ContBlock);
1944 EmitBlock(ContBlock, true);
1945 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001946 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001947 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001948}
1949
1950void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001951 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001952 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
1953 PrePostActionTy &) {
1954 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1955 };
Alexey Bataev3392d762016-02-16 11:18:12 +00001956 {
1957 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00001958 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1959 S.hasCancel());
1960 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001961
1962 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001963 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001964 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1965 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001966}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001967
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001968void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001969 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001970 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
1971 PrePostActionTy &) {
1972 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1973 };
Alexey Bataev3392d762016-02-16 11:18:12 +00001974 {
1975 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00001976 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1977 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001978
1979 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001980 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001981 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1982 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001983}
1984
Alexey Bataev2df54a02015-03-12 08:53:29 +00001985static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1986 const Twine &Name,
1987 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001988 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001989 if (Init)
1990 CGF.EmitScalarInit(Init, LVal);
1991 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001992}
1993
Alexey Bataev3392d762016-02-16 11:18:12 +00001994void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001995 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1996 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001997 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001998 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
1999 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002000 auto &C = CGF.CGM.getContext();
2001 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2002 // Emit helper vars inits.
2003 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2004 CGF.Builder.getInt32(0));
2005 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2006 : CGF.Builder.getInt32(0);
2007 LValue UB =
2008 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2009 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2010 CGF.Builder.getInt32(1));
2011 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2012 CGF.Builder.getInt32(0));
2013 // Loop counter.
2014 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2015 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2016 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2017 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2018 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2019 // Generate condition for loop.
2020 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2021 OK_Ordinary, S.getLocStart(),
2022 /*fpContractable=*/false);
2023 // Increment for loop counter.
2024 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2025 S.getLocStart());
2026 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2027 // Iterate through all sections and emit a switch construct:
2028 // switch (IV) {
2029 // case 0:
2030 // <SectionStmt[0]>;
2031 // break;
2032 // ...
2033 // case <NumSection> - 1:
2034 // <SectionStmt[<NumSection> - 1]>;
2035 // break;
2036 // }
2037 // .omp.sections.exit:
2038 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2039 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2040 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2041 CS == nullptr ? 1 : CS->size());
2042 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002043 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002044 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002045 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2046 CGF.EmitBlock(CaseBB);
2047 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002048 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002049 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002050 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002051 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002052 } else {
2053 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2054 CGF.EmitBlock(CaseBB);
2055 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2056 CGF.EmitStmt(Stmt);
2057 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002058 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002059 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002060 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002061
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002062 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2063 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002064 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002065 // initialization of firstprivate variables and post-update of lastprivate
2066 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002067 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2068 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2069 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002070 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002071 CGF.EmitOMPPrivateClause(S, LoopScope);
2072 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2073 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2074 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002075
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002076 // Emit static non-chunked loop.
2077 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2078 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
2079 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2080 UB.getAddress(), ST.getAddress());
2081 // UB = min(UB, GlobalUB);
2082 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2083 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2084 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2085 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2086 // IV = LB;
2087 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2088 // while (idx <= UB) { BODY; ++idx; }
2089 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2090 [](CodeGenFunction &) {});
2091 // Tell the runtime we are done.
2092 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
2093 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002094 // Emit post-update of the reduction variables if IsLastIter != 0.
2095 emitPostUpdateForReductionClause(
2096 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2097 return CGF.Builder.CreateIsNotNull(
2098 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2099 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002100
2101 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2102 if (HasLastprivates)
2103 CGF.EmitOMPLastprivateClauseFinal(
2104 S, CGF.Builder.CreateIsNotNull(
2105 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002106 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002107
2108 bool HasCancel = false;
2109 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2110 HasCancel = OSD->hasCancel();
2111 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2112 HasCancel = OPSD->hasCancel();
2113 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2114 HasCancel);
2115 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2116 // clause. Otherwise the barrier will be generated by the codegen for the
2117 // directive.
2118 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002119 // Emit implicit barrier to synchronize threads and avoid data races on
2120 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002121 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2122 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002123 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002124}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002125
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002126void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002127 {
2128 OMPLexicalScope Scope(*this, S);
2129 EmitSections(S);
2130 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002131 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002132 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002133 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2134 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002135 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002136}
2137
2138void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002139 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002140 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002141 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002142 OMPLexicalScope Scope(*this, S);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002143 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2144 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002145}
2146
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002147void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002148 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002149 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002150 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002151 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002152 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002153 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002154 // Build a list of copyprivate variables along with helper expressions
2155 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002156 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002157 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002158 DestExprs.append(C->destination_exprs().begin(),
2159 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002160 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002161 AssignmentOps.append(C->assignment_ops().begin(),
2162 C->assignment_ops().end());
2163 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002164 // Emit code for 'single' region along with 'copyprivate' clauses
2165 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2166 Action.Enter(CGF);
2167 OMPPrivateScope SingleScope(CGF);
2168 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2169 CGF.EmitOMPPrivateClause(S, SingleScope);
2170 (void)SingleScope.Privatize();
2171 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2172 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002173 {
2174 OMPLexicalScope Scope(*this, S);
Alexey Bataev3392d762016-02-16 11:18:12 +00002175 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2176 CopyprivateVars, DestExprs,
2177 SrcExprs, AssignmentOps);
2178 }
2179 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2180 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002181 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002182 CGM.getOpenMPRuntime().emitBarrierCall(
2183 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002184 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002185 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002186}
2187
Alexey Bataev8d690652014-12-04 07:23:53 +00002188void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002189 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2190 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002191 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002192 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002193 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002194 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002195}
2196
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002197void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002198 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2199 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002200 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002201 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002202 Expr *Hint = nullptr;
2203 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2204 Hint = HintClause->getHint();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002205 OMPLexicalScope Scope(*this, S);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002206 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2207 S.getDirectiveName().getAsString(),
2208 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002209}
2210
Alexey Bataev671605e2015-04-13 05:28:11 +00002211void CodeGenFunction::EmitOMPParallelForDirective(
2212 const OMPParallelForDirective &S) {
2213 // Emit directive as a combined directive that consists of two implicit
2214 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002215 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev671605e2015-04-13 05:28:11 +00002216 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002217 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002218 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002219}
2220
Alexander Musmane4e893b2014-09-23 09:33:00 +00002221void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002222 const OMPParallelForSimdDirective &S) {
2223 // Emit directive as a combined directive that consists of two implicit
2224 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002225 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002226 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002227 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002228 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002229}
2230
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002231void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002232 const OMPParallelSectionsDirective &S) {
2233 // Emit directive as a combined directive that consists of two implicit
2234 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002235 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2236 CGF.EmitSections(S);
2237 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002238 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002239}
2240
Alexey Bataev62b63b12015-03-10 07:28:44 +00002241void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2242 // Emit outlined function for task construct.
2243 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2244 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2245 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002246 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002247 // The first function argument for tasks is a thread id, the second one is a
2248 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002249 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2250 // Get list of private variables.
2251 llvm::SmallVector<const Expr *, 8> PrivateVars;
2252 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002253 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002254 auto IRef = C->varlist_begin();
2255 for (auto *IInit : C->private_copies()) {
2256 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2257 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2258 PrivateVars.push_back(*IRef);
2259 PrivateCopies.push_back(IInit);
2260 }
2261 ++IRef;
2262 }
2263 }
2264 EmittedAsPrivate.clear();
2265 // Get list of firstprivate variables.
2266 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2267 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2268 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002269 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002270 auto IRef = C->varlist_begin();
2271 auto IElemInitRef = C->inits().begin();
2272 for (auto *IInit : C->private_copies()) {
2273 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2274 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2275 FirstprivateVars.push_back(*IRef);
2276 FirstprivateCopies.push_back(IInit);
2277 FirstprivateInits.push_back(*IElemInitRef);
2278 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002279 ++IRef;
2280 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002281 }
2282 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002283 // Build list of dependences.
2284 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2285 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002286 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002287 for (auto *IRef : C->varlists()) {
2288 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2289 }
2290 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002291 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002292 CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002293 // Set proper addresses for generated private copies.
2294 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002295 {
2296 OMPPrivateScope Scope(CGF);
2297 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
2298 auto *CopyFn = CGF.Builder.CreateLoad(
2299 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2300 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2301 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2302 // Map privates.
2303 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2304 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2305 CallArgs.push_back(PrivatesPtr);
2306 for (auto *E : PrivateVars) {
2307 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2308 Address PrivatePtr =
2309 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2310 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2311 CallArgs.push_back(PrivatePtr.getPointer());
2312 }
2313 for (auto *E : FirstprivateVars) {
2314 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2315 Address PrivatePtr =
2316 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2317 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2318 CallArgs.push_back(PrivatePtr.getPointer());
2319 }
2320 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2321 for (auto &&Pair : PrivatePtrs) {
2322 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2323 CGF.getContext().getDeclAlign(Pair.first));
2324 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2325 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002326 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002327 (void)Scope.Privatize();
2328 if (*PartId) {
2329 // TODO: emit code for untied tasks.
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002330 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002331 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002332 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002333 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002334 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2335 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002336 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002337 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002338 // Check if the task is final
2339 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002340 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002341 // If the condition constant folds and can be elided, try to avoid emitting
2342 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002343 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002344 bool CondConstant;
2345 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2346 Final.setInt(CondConstant);
2347 else
2348 Final.setPointer(EvaluateExprAsBool(Cond));
2349 } else {
2350 // By default the task is not final.
2351 Final.setInt(/*IntVal=*/false);
2352 }
2353 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002354 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002355 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2356 if (C->getNameModifier() == OMPD_unknown ||
2357 C->getNameModifier() == OMPD_task) {
2358 IfCond = C->getCondition();
2359 break;
2360 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002361 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002362 OMPLexicalScope Scope(*this, S);
Alexey Bataev9e034042015-05-05 04:05:12 +00002363 CGM.getOpenMPRuntime().emitTaskCall(
2364 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002365 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002366 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002367}
2368
Alexey Bataev9f797f32015-02-05 05:57:51 +00002369void CodeGenFunction::EmitOMPTaskyieldDirective(
2370 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002371 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002372}
2373
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002374void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002375 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002376}
2377
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002378void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2379 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002380}
2381
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002382void CodeGenFunction::EmitOMPTaskgroupDirective(
2383 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002384 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2385 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002386 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002387 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002388 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002389 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2390}
2391
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002392void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002393 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002394 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002395 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2396 FlushClause->varlist_end());
2397 }
2398 return llvm::None;
2399 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002400}
2401
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002402void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2403 // Emit the loop iteration variable.
2404 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2405 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2406 EmitVarDecl(*IVDecl);
2407
2408 // Emit the iterations count variable.
2409 // If it is not a variable, Sema decided to calculate iterations count on each
2410 // iteration (e.g., it is foldable into a constant).
2411 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2412 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2413 // Emit calculation of the iterations count.
2414 EmitIgnoredExpr(S.getCalcLastIteration());
2415 }
2416
2417 auto &RT = CGM.getOpenMPRuntime();
2418
2419 // Check pre-condition.
2420 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002421 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002422 // Skip the entire loop if we don't meet the precondition.
2423 // If the condition constant folds and can be elided, avoid emitting the
2424 // whole loop.
2425 bool CondConstant;
2426 llvm::BasicBlock *ContBlock = nullptr;
2427 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2428 if (!CondConstant)
2429 return;
2430 } else {
2431 auto *ThenBlock = createBasicBlock("omp.precond.then");
2432 ContBlock = createBasicBlock("omp.precond.end");
2433 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2434 getProfileCount(&S));
2435 EmitBlock(ThenBlock);
2436 incrementProfileCounter(&S);
2437 }
2438
2439 // Emit 'then' code.
2440 {
2441 // Emit helper vars inits.
2442 LValue LB =
2443 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2444 LValue UB =
2445 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2446 LValue ST =
2447 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2448 LValue IL =
2449 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2450
2451 OMPPrivateScope LoopScope(*this);
2452 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
2453 S.private_counters());
2454 (void)LoopScope.Privatize();
2455
2456 // Detect the distribute schedule kind and chunk.
2457 llvm::Value *Chunk = nullptr;
2458 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2459 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2460 ScheduleKind = C->getDistScheduleKind();
2461 if (const auto *Ch = C->getChunkSize()) {
2462 Chunk = EmitScalarExpr(Ch);
2463 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2464 S.getIterationVariable()->getType(),
2465 S.getLocStart());
2466 }
2467 }
2468 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2469 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2470
2471 // OpenMP [2.10.8, distribute Construct, Description]
2472 // If dist_schedule is specified, kind must be static. If specified,
2473 // iterations are divided into chunks of size chunk_size, chunks are
2474 // assigned to the teams of the league in a round-robin fashion in the
2475 // order of the team number. When no chunk_size is specified, the
2476 // iteration space is divided into chunks that are approximately equal
2477 // in size, and at most one chunk is distributed to each team of the
2478 // league. The size of the chunks is unspecified in this case.
2479 if (RT.isStaticNonchunked(ScheduleKind,
2480 /* Chunked */ Chunk != nullptr)) {
2481 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2482 IVSize, IVSigned, /* Ordered = */ false,
2483 IL.getAddress(), LB.getAddress(),
2484 UB.getAddress(), ST.getAddress());
2485 auto LoopExit =
2486 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2487 // UB = min(UB, GlobalUB);
2488 EmitIgnoredExpr(S.getEnsureUpperBound());
2489 // IV = LB;
2490 EmitIgnoredExpr(S.getInit());
2491 // while (idx <= UB) { BODY; ++idx; }
2492 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2493 S.getInc(),
2494 [&S, LoopExit](CodeGenFunction &CGF) {
2495 CGF.EmitOMPLoopBody(S, LoopExit);
2496 CGF.EmitStopPoint(&S);
2497 },
2498 [](CodeGenFunction &) {});
2499 EmitBlock(LoopExit.getBlock());
2500 // Tell the runtime we are done.
2501 RT.emitForStaticFinish(*this, S.getLocStart());
2502 } else {
2503 // Emit the outer loop, which requests its work chunk [LB..UB] from
2504 // runtime and runs the inner loop to process it.
2505 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2506 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2507 IL.getAddress(), Chunk);
2508 }
2509 }
2510
2511 // We're now done with the loop, so jump to the continuation block.
2512 if (ContBlock) {
2513 EmitBranch(ContBlock);
2514 EmitBlock(ContBlock, true);
2515 }
2516 }
2517}
2518
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002519void CodeGenFunction::EmitOMPDistributeDirective(
2520 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002521 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002522 CGF.EmitOMPDistributeLoop(S);
2523 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002524 OMPLexicalScope Scope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002525 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2526 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002527}
2528
Alexey Bataev5f600d62015-09-29 03:48:57 +00002529static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2530 const CapturedStmt *S) {
2531 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2532 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2533 CGF.CapturedStmtInfo = &CapStmtInfo;
2534 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2535 Fn->addFnAttr(llvm::Attribute::NoInline);
2536 return Fn;
2537}
2538
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002539void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002540 if (!S.getAssociatedStmt())
2541 return;
Alexey Bataev5f600d62015-09-29 03:48:57 +00002542 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002543 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2544 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002545 if (C) {
2546 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2547 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2548 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2549 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2550 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2551 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002552 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002553 CGF.EmitStmt(
2554 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2555 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002556 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002557 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002558 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002559}
2560
Alexey Bataevb57056f2015-01-22 06:17:56 +00002561static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002562 QualType SrcType, QualType DestType,
2563 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002564 assert(CGF.hasScalarEvaluationKind(DestType) &&
2565 "DestType must have scalar evaluation kind.");
2566 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2567 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002568 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2569 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002570 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002571 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002572}
2573
2574static CodeGenFunction::ComplexPairTy
2575convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002576 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002577 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2578 "DestType must have complex evaluation kind.");
2579 CodeGenFunction::ComplexPairTy ComplexVal;
2580 if (Val.isScalar()) {
2581 // Convert the input element to the element type of the complex.
2582 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002583 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2584 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002585 ComplexVal = CodeGenFunction::ComplexPairTy(
2586 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2587 } else {
2588 assert(Val.isComplex() && "Must be a scalar or complex.");
2589 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2590 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2591 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002592 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002593 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002594 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002595 }
2596 return ComplexVal;
2597}
2598
Alexey Bataev5e018f92015-04-23 06:35:10 +00002599static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2600 LValue LVal, RValue RVal) {
2601 if (LVal.isGlobalReg()) {
2602 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2603 } else {
2604 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2605 : llvm::Monotonic,
2606 LVal.isVolatile(), /*IsInit=*/false);
2607 }
2608}
2609
Alexey Bataev8524d152016-01-21 12:35:58 +00002610void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2611 QualType RValTy, SourceLocation Loc) {
2612 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002613 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002614 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2615 *this, RVal, RValTy, LVal.getType(), Loc)),
2616 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002617 break;
2618 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002619 EmitStoreOfComplex(
2620 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002621 /*isInit=*/false);
2622 break;
2623 case TEK_Aggregate:
2624 llvm_unreachable("Must be a scalar or complex.");
2625 }
2626}
2627
Alexey Bataevb57056f2015-01-22 06:17:56 +00002628static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2629 const Expr *X, const Expr *V,
2630 SourceLocation Loc) {
2631 // v = x;
2632 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2633 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2634 LValue XLValue = CGF.EmitLValue(X);
2635 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002636 RValue Res = XLValue.isGlobalReg()
2637 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2638 : CGF.EmitAtomicLoad(XLValue, Loc,
2639 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002640 : llvm::Monotonic,
2641 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002642 // OpenMP, 2.12.6, atomic Construct
2643 // Any atomic construct with a seq_cst clause forces the atomically
2644 // performed operation to include an implicit flush operation without a
2645 // list.
2646 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002647 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002648 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002649}
2650
Alexey Bataevb8329262015-02-27 06:33:30 +00002651static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2652 const Expr *X, const Expr *E,
2653 SourceLocation Loc) {
2654 // x = expr;
2655 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002656 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002657 // OpenMP, 2.12.6, atomic Construct
2658 // Any atomic construct with a seq_cst clause forces the atomically
2659 // performed operation to include an implicit flush operation without a
2660 // list.
2661 if (IsSeqCst)
2662 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2663}
2664
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002665static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2666 RValue Update,
2667 BinaryOperatorKind BO,
2668 llvm::AtomicOrdering AO,
2669 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002670 auto &Context = CGF.CGM.getContext();
2671 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002672 // expression is simple and atomic is allowed for the given type for the
2673 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002674 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002675 !Update.getScalarVal()->getType()->isIntegerTy() ||
2676 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2677 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002678 X.getAddress().getElementType())) ||
2679 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002680 !Context.getTargetInfo().hasBuiltinAtomic(
2681 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002682 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002683
2684 llvm::AtomicRMWInst::BinOp RMWOp;
2685 switch (BO) {
2686 case BO_Add:
2687 RMWOp = llvm::AtomicRMWInst::Add;
2688 break;
2689 case BO_Sub:
2690 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002691 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002692 RMWOp = llvm::AtomicRMWInst::Sub;
2693 break;
2694 case BO_And:
2695 RMWOp = llvm::AtomicRMWInst::And;
2696 break;
2697 case BO_Or:
2698 RMWOp = llvm::AtomicRMWInst::Or;
2699 break;
2700 case BO_Xor:
2701 RMWOp = llvm::AtomicRMWInst::Xor;
2702 break;
2703 case BO_LT:
2704 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2705 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2706 : llvm::AtomicRMWInst::Max)
2707 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2708 : llvm::AtomicRMWInst::UMax);
2709 break;
2710 case BO_GT:
2711 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2712 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2713 : llvm::AtomicRMWInst::Min)
2714 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2715 : llvm::AtomicRMWInst::UMin);
2716 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002717 case BO_Assign:
2718 RMWOp = llvm::AtomicRMWInst::Xchg;
2719 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002720 case BO_Mul:
2721 case BO_Div:
2722 case BO_Rem:
2723 case BO_Shl:
2724 case BO_Shr:
2725 case BO_LAnd:
2726 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002727 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002728 case BO_PtrMemD:
2729 case BO_PtrMemI:
2730 case BO_LE:
2731 case BO_GE:
2732 case BO_EQ:
2733 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002734 case BO_AddAssign:
2735 case BO_SubAssign:
2736 case BO_AndAssign:
2737 case BO_OrAssign:
2738 case BO_XorAssign:
2739 case BO_MulAssign:
2740 case BO_DivAssign:
2741 case BO_RemAssign:
2742 case BO_ShlAssign:
2743 case BO_ShrAssign:
2744 case BO_Comma:
2745 llvm_unreachable("Unsupported atomic update operation");
2746 }
2747 auto *UpdateVal = Update.getScalarVal();
2748 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2749 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002750 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002751 X.getType()->hasSignedIntegerRepresentation());
2752 }
John McCall7f416cc2015-09-08 08:05:57 +00002753 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002754 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002755}
2756
Alexey Bataev5e018f92015-04-23 06:35:10 +00002757std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002758 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2759 llvm::AtomicOrdering AO, SourceLocation Loc,
2760 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2761 // Update expressions are allowed to have the following forms:
2762 // x binop= expr; -> xrval + expr;
2763 // x++, ++x -> xrval + 1;
2764 // x--, --x -> xrval - 1;
2765 // x = x binop expr; -> xrval binop expr
2766 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002767 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2768 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002769 if (X.isGlobalReg()) {
2770 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2771 // 'xrval'.
2772 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2773 } else {
2774 // Perform compare-and-swap procedure.
2775 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002776 }
2777 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002778 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002779}
2780
2781static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2782 const Expr *X, const Expr *E,
2783 const Expr *UE, bool IsXLHSInRHSPart,
2784 SourceLocation Loc) {
2785 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2786 "Update expr in 'atomic update' must be a binary operator.");
2787 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2788 // Update expressions are allowed to have the following forms:
2789 // x binop= expr; -> xrval + expr;
2790 // x++, ++x -> xrval + 1;
2791 // x--, --x -> xrval - 1;
2792 // x = x binop expr; -> xrval binop expr
2793 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002794 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002795 LValue XLValue = CGF.EmitLValue(X);
2796 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002797 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002798 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2799 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2800 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2801 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2802 auto Gen =
2803 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2804 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2805 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2806 return CGF.EmitAnyExpr(UE);
2807 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002808 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2809 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2810 // OpenMP, 2.12.6, atomic Construct
2811 // Any atomic construct with a seq_cst clause forces the atomically
2812 // performed operation to include an implicit flush operation without a
2813 // list.
2814 if (IsSeqCst)
2815 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2816}
2817
2818static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002819 QualType SourceType, QualType ResType,
2820 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002821 switch (CGF.getEvaluationKind(ResType)) {
2822 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002823 return RValue::get(
2824 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002825 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002826 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002827 return RValue::getComplex(Res.first, Res.second);
2828 }
2829 case TEK_Aggregate:
2830 break;
2831 }
2832 llvm_unreachable("Must be a scalar or complex.");
2833}
2834
2835static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2836 bool IsPostfixUpdate, const Expr *V,
2837 const Expr *X, const Expr *E,
2838 const Expr *UE, bool IsXLHSInRHSPart,
2839 SourceLocation Loc) {
2840 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2841 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2842 RValue NewVVal;
2843 LValue VLValue = CGF.EmitLValue(V);
2844 LValue XLValue = CGF.EmitLValue(X);
2845 RValue ExprRValue = CGF.EmitAnyExpr(E);
2846 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2847 QualType NewVValType;
2848 if (UE) {
2849 // 'x' is updated with some additional value.
2850 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2851 "Update expr in 'atomic capture' must be a binary operator.");
2852 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2853 // Update expressions are allowed to have the following forms:
2854 // x binop= expr; -> xrval + expr;
2855 // x++, ++x -> xrval + 1;
2856 // x--, --x -> xrval - 1;
2857 // x = x binop expr; -> xrval binop expr
2858 // x = expr Op x; - > expr binop xrval;
2859 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2860 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2861 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2862 NewVValType = XRValExpr->getType();
2863 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2864 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2865 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2866 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2867 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2868 RValue Res = CGF.EmitAnyExpr(UE);
2869 NewVVal = IsPostfixUpdate ? XRValue : Res;
2870 return Res;
2871 };
2872 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2873 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2874 if (Res.first) {
2875 // 'atomicrmw' instruction was generated.
2876 if (IsPostfixUpdate) {
2877 // Use old value from 'atomicrmw'.
2878 NewVVal = Res.second;
2879 } else {
2880 // 'atomicrmw' does not provide new value, so evaluate it using old
2881 // value of 'x'.
2882 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2883 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2884 NewVVal = CGF.EmitAnyExpr(UE);
2885 }
2886 }
2887 } else {
2888 // 'x' is simply rewritten with some 'expr'.
2889 NewVValType = X->getType().getNonReferenceType();
2890 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002891 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002892 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2893 NewVVal = XRValue;
2894 return ExprRValue;
2895 };
2896 // Try to perform atomicrmw xchg, otherwise simple exchange.
2897 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2898 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2899 Loc, Gen);
2900 if (Res.first) {
2901 // 'atomicrmw' instruction was generated.
2902 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2903 }
2904 }
2905 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002906 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002907 // OpenMP, 2.12.6, atomic Construct
2908 // Any atomic construct with a seq_cst clause forces the atomically
2909 // performed operation to include an implicit flush operation without a
2910 // list.
2911 if (IsSeqCst)
2912 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2913}
2914
Alexey Bataevb57056f2015-01-22 06:17:56 +00002915static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002916 bool IsSeqCst, bool IsPostfixUpdate,
2917 const Expr *X, const Expr *V, const Expr *E,
2918 const Expr *UE, bool IsXLHSInRHSPart,
2919 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002920 switch (Kind) {
2921 case OMPC_read:
2922 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2923 break;
2924 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002925 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2926 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002927 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002928 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002929 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2930 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002931 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002932 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2933 IsXLHSInRHSPart, Loc);
2934 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002935 case OMPC_if:
2936 case OMPC_final:
2937 case OMPC_num_threads:
2938 case OMPC_private:
2939 case OMPC_firstprivate:
2940 case OMPC_lastprivate:
2941 case OMPC_reduction:
2942 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002943 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002944 case OMPC_collapse:
2945 case OMPC_default:
2946 case OMPC_seq_cst:
2947 case OMPC_shared:
2948 case OMPC_linear:
2949 case OMPC_aligned:
2950 case OMPC_copyin:
2951 case OMPC_copyprivate:
2952 case OMPC_flush:
2953 case OMPC_proc_bind:
2954 case OMPC_schedule:
2955 case OMPC_ordered:
2956 case OMPC_nowait:
2957 case OMPC_untied:
2958 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002959 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002960 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002961 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002962 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002963 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002964 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002965 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002966 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002967 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002968 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002969 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002970 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002971 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002972 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002973 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002974 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2975 }
2976}
2977
2978void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002979 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002980 OpenMPClauseKind Kind = OMPC_unknown;
2981 for (auto *C : S.clauses()) {
2982 // Find first clause (skip seq_cst clause, if it is first).
2983 if (C->getClauseKind() != OMPC_seq_cst) {
2984 Kind = C->getClauseKind();
2985 break;
2986 }
2987 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002988
2989 const auto *CS =
2990 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002991 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002992 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002993 }
2994 // Processing for statements under 'atomic capture'.
2995 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2996 for (const auto *C : Compound->body()) {
2997 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2998 enterFullExpression(EWC);
2999 }
3000 }
3001 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003002
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003003 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3004 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003005 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003006 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3007 S.getV(), S.getExpr(), S.getUpdateExpr(),
3008 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003009 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003010 OMPLexicalScope Scope(*this, S);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003011 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003012}
3013
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003014std::pair<llvm::Function * /*OutlinedFn*/, llvm::Constant * /*OutlinedFnID*/>
3015CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
3016 CodeGenModule &CGM, const OMPTargetDirective &S, StringRef ParentName,
3017 bool IsOffloadEntry) {
3018 llvm::Function *OutlinedFn = nullptr;
3019 llvm::Constant *OutlinedFnID = nullptr;
3020 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3021 OMPPrivateScope PrivateScope(CGF);
3022 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3023 CGF.EmitOMPPrivateClause(S, PrivateScope);
3024 (void)PrivateScope.Privatize();
3025
3026 Action.Enter(CGF);
3027 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3028 };
3029 // Emit target region as a standalone region.
3030 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3031 S, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen);
3032 return std::make_pair(OutlinedFn, OutlinedFnID);
3033}
3034
Samuel Antaobed3c462015-10-02 16:14:20 +00003035void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Samuel Antaobed3c462015-10-02 16:14:20 +00003036 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3037
3038 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003039 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003040
Samuel Antaoee8fb302016-01-06 13:42:12 +00003041 llvm::Function *Fn = nullptr;
3042 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003043
3044 // Check if we have any if clause associated with the directive.
3045 const Expr *IfCond = nullptr;
3046
3047 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3048 IfCond = C->getCondition();
3049 }
3050
3051 // Check if we have any device clause associated with the directive.
3052 const Expr *Device = nullptr;
3053 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3054 Device = C->getDevice();
3055 }
3056
Samuel Antaoee8fb302016-01-06 13:42:12 +00003057 // Check if we have an if clause whose conditional always evaluates to false
3058 // or if we do not have any targets specified. If so the target region is not
3059 // an offload entry point.
3060 bool IsOffloadEntry = true;
3061 if (IfCond) {
3062 bool Val;
3063 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3064 IsOffloadEntry = false;
3065 }
3066 if (CGM.getLangOpts().OMPTargetTriples.empty())
3067 IsOffloadEntry = false;
3068
3069 assert(CurFuncDecl && "No parent declaration for target region!");
3070 StringRef ParentName;
3071 // In case we have Ctors/Dtors we use the complete type variant to produce
3072 // the mangling of the device outlined kernel.
3073 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
3074 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3075 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
3076 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3077 else
3078 ParentName =
3079 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
3080
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003081 std::tie(Fn, FnID) = EmitOMPTargetDirectiveOutlinedFunction(
3082 CGM, S, ParentName, IsOffloadEntry);
3083 OMPLexicalScope Scope(*this, S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003084 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003085 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003086}
3087
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003088static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3089 const OMPExecutableDirective &S,
3090 OpenMPDirectiveKind InnermostKind,
3091 const RegionCodeGenTy &CodeGen) {
3092 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003093 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3094 emitParallelOrTeamsOutlinedFunction(S,
3095 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003096
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003097 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3098 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3099 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3100 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003101 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3102 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003103
Carlo Bertollic6872252016-04-04 15:55:02 +00003104 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3105 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003106 }
3107
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003108 OMPLexicalScope Scope(CGF, S);
3109 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3110 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003111 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3112 CapturedVars);
3113}
3114
3115void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003116 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003117 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003118 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003119 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3120 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003121 (void)PrivateScope.Privatize();
3122 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3123 };
3124 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003125}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003126
3127void CodeGenFunction::EmitOMPCancellationPointDirective(
3128 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003129 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3130 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003131}
3132
Alexey Bataev80909872015-07-02 11:25:17 +00003133void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003134 const Expr *IfCond = nullptr;
3135 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3136 if (C->getNameModifier() == OMPD_unknown ||
3137 C->getNameModifier() == OMPD_cancel) {
3138 IfCond = C->getCondition();
3139 break;
3140 }
3141 }
3142 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003143 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003144}
3145
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003146CodeGenFunction::JumpDest
3147CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
3148 if (Kind == OMPD_parallel || Kind == OMPD_task)
3149 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003150 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003151 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003152 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003153}
Michael Wong65f367f2015-07-21 13:44:28 +00003154
3155// Generate the instructions for '#pragma omp target data' directive.
3156void CodeGenFunction::EmitOMPTargetDataDirective(
3157 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00003158 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003159 OMPLexicalScope Scope(*this, S);
Michael Wongb5c16982015-08-11 04:52:01 +00003160 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003161 *this, OMPD_target_data, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3162 CGF.EmitStmt(
3163 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3164 });
Michael Wong65f367f2015-07-21 13:44:28 +00003165}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003166
Samuel Antaodf67fc42016-01-19 19:15:56 +00003167void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3168 const OMPTargetEnterDataDirective &S) {
3169 // TODO: codegen for target enter data.
3170}
3171
Samuel Antao72590762016-01-19 20:04:50 +00003172void CodeGenFunction::EmitOMPTargetExitDataDirective(
3173 const OMPTargetExitDataDirective &S) {
3174 // TODO: codegen for target exit data.
3175}
3176
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003177void CodeGenFunction::EmitOMPTargetParallelDirective(
3178 const OMPTargetParallelDirective &S) {
3179 // TODO: codegen for target parallel.
3180}
3181
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003182void CodeGenFunction::EmitOMPTargetParallelForDirective(
3183 const OMPTargetParallelForDirective &S) {
3184 // TODO: codegen for target parallel for.
3185}
3186
Alexey Bataev49f6e782015-12-01 04:18:41 +00003187void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
3188 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003189 OMPLexicalScope Scope(*this, S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003190 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003191 *this, OMPD_taskloop, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003192 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003193 CGF.EmitStmt(
3194 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3195 });
Alexey Bataev49f6e782015-12-01 04:18:41 +00003196}
3197
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003198void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3199 const OMPTaskLoopSimdDirective &S) {
3200 // emit the code inside the construct for now
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003201 OMPLexicalScope Scope(*this, S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003202 CGM.getOpenMPRuntime().emitInlinedDirective(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003203 *this, OMPD_taskloop_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003204 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003205 CGF.EmitStmt(
3206 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3207 });
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003208}
3209