blob: 7f4e19577ab2ad7eb3e2b35cd38bce775e5a979b [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022using namespace clang;
23using namespace CodeGen;
24
Alexey Bataev3392d762016-02-16 11:18:12 +000025namespace {
26/// Lexical scope for OpenMP executable constructs, that handles correct codegen
27/// for captured expressions.
28class OMPLexicalScope {
29 CodeGenFunction::LexicalScope Scope;
30 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
47
Alexey Bataev3392d762016-02-16 11:18:12 +000048public:
49 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
50 : Scope(CGF, S.getSourceRange()) {
51 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000052 }
53};
54} // namespace
55
Alexey Bataev1189bd02016-01-26 12:20:39 +000056llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
57 auto &C = getContext();
58 llvm::Value *Size = nullptr;
59 auto SizeInChars = C.getTypeSizeInChars(Ty);
60 if (SizeInChars.isZero()) {
61 // getTypeSizeInChars() returns 0 for a VLA.
62 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
63 llvm::Value *ArraySize;
64 std::tie(ArraySize, Ty) = getVLASize(VAT);
65 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
66 }
67 SizeInChars = C.getTypeSizeInChars(Ty);
68 if (SizeInChars.isZero())
69 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
70 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
71 } else
72 Size = CGM.getSize(SizeInChars);
73 return Size;
74}
75
Alexey Bataev2377fe92015-09-10 08:12:02 +000076void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000077 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000078 const RecordDecl *RD = S.getCapturedRecordDecl();
79 auto CurField = RD->field_begin();
80 auto CurCap = S.captures().begin();
81 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
82 E = S.capture_init_end();
83 I != E; ++I, ++CurField, ++CurCap) {
84 if (CurField->hasCapturedVLAType()) {
85 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000086 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000087 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000088 } else if (CurCap->capturesThis())
89 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000090 else if (CurCap->capturesVariableByCopy())
91 CapturedVars.push_back(
92 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
93 else {
94 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000095 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000096 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000097 }
98}
99
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000100static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
101 StringRef Name, LValue AddrLV,
102 bool isReferenceType = false) {
103 ASTContext &Ctx = CGF.getContext();
104
105 auto *CastedPtr = CGF.EmitScalarConversion(
106 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
107 Ctx.getPointerType(DstType), SourceLocation());
108 auto TmpAddr =
109 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
110 .getAddress();
111
112 // If we are dealing with references we need to return the address of the
113 // reference instead of the reference of the value.
114 if (isReferenceType) {
115 QualType RefType = Ctx.getLValueReferenceType(DstType);
116 auto *RefVal = TmpAddr.getPointer();
117 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
118 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
119 CGF.EmitScalarInit(RefVal, TmpLVal);
120 }
121
122 return TmpAddr;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 assert(
128 CapturedStmtInfo &&
129 "CapturedStmtInfo should be set when generating the captured function");
130 const CapturedDecl *CD = S.getCapturedDecl();
131 const RecordDecl *RD = S.getCapturedRecordDecl();
132 assert(CD->hasBody() && "missing CapturedDecl body");
133
134 // Build the argument list.
135 ASTContext &Ctx = CGM.getContext();
136 FunctionArgList Args;
137 Args.append(CD->param_begin(),
138 std::next(CD->param_begin(), CD->getContextParamPosition()));
139 auto I = S.captures().begin();
140 for (auto *FD : RD->fields()) {
141 QualType ArgType = FD->getType();
142 IdentifierInfo *II = nullptr;
143 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000144
145 // If this is a capture by copy and the type is not a pointer, the outlined
146 // function argument type should be uintptr and the value properly casted to
147 // uintptr. This is necessary given that the runtime library is only able to
148 // deal with pointers. We can pass in the same way the VLA type sizes to the
149 // outlined function.
150 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
151 I->capturesVariableArrayType())
152 ArgType = Ctx.getUIntPtrType();
153
154 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000155 CapVar = I->getCapturedVar();
156 II = CapVar->getIdentifier();
157 } else if (I->capturesThis())
158 II = &getContext().Idents.get("this");
159 else {
160 assert(I->capturesVariableArrayType());
161 II = &getContext().Idents.get("vla");
162 }
163 if (ArgType->isVariablyModifiedType())
164 ArgType = getContext().getVariableArrayDecayedType(ArgType);
165 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
166 FD->getLocation(), II, ArgType));
167 ++I;
168 }
169 Args.append(
170 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
171 CD->param_end());
172
173 // Create the function declaration.
174 FunctionType::ExtInfo ExtInfo;
175 const CGFunctionInfo &FuncInfo =
176 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
177 /*IsVariadic=*/false);
178 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
179
180 llvm::Function *F = llvm::Function::Create(
181 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
182 CapturedStmtInfo->getHelperName(), &CGM.getModule());
183 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
184 if (CD->isNothrow())
185 F->addFnAttr(llvm::Attribute::NoUnwind);
186
187 // Generate the function.
188 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
189 CD->getBody()->getLocStart());
190 unsigned Cnt = CD->getContextParamPosition();
191 I = S.captures().begin();
192 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000193 // If we are capturing a pointer by copy we don't need to do anything, just
194 // use the value that we get from the arguments.
195 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
196 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000197 ++Cnt;
198 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000199 continue;
200 }
201
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 LValue ArgLVal =
203 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
204 AlignmentSource::Decl);
205 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206 LValue CastedArgLVal =
207 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
208 Args[Cnt]->getName(), ArgLVal),
209 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000210 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000211 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000212 auto VAT = FD->getCapturedVLAType();
213 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
214 } else if (I->capturesVariable()) {
215 auto *Var = I->getCapturedVar();
216 QualType VarTy = Var->getType();
217 Address ArgAddr = ArgLVal.getAddress();
218 if (!VarTy->isReferenceType()) {
219 ArgAddr = EmitLoadOfReference(
220 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
221 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000222 setAddrOfLocalVar(
223 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224 } else if (I->capturesVariableByCopy()) {
225 assert(!FD->getType()->isAnyPointerType() &&
226 "Not expecting a captured pointer.");
227 auto *Var = I->getCapturedVar();
228 QualType VarTy = Var->getType();
229 setAddrOfLocalVar(I->getCapturedVar(),
230 castValueFromUintptr(*this, FD->getType(),
231 Args[Cnt]->getName(), ArgLVal,
232 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 } else {
234 // If 'this' is captured, load it into CXXThisValue.
235 assert(I->capturesThis());
236 CXXThisValue =
237 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
238 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000239 ++Cnt;
240 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000241 }
242
Serge Pavlov3a561452015-12-06 14:32:39 +0000243 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 CapturedStmtInfo->EmitBody(*this, CD->getBody());
245 FinishFunction(CD->getBodyRBrace());
246
247 return F;
248}
249
Alexey Bataev9959db52014-05-06 10:08:46 +0000250//===----------------------------------------------------------------------===//
251// OpenMP Directive Emission
252//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000253void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000254 Address DestAddr, Address SrcAddr, QualType OriginalType,
255 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000256 // Perform element-by-element initialization.
257 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000258
259 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000260 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000261 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
262 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
263
264 auto SrcBegin = SrcAddr.getPointer();
265 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000266 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000267 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
268 // The basic structure here is a while-do loop.
269 auto BodyBB = createBasicBlock("omp.arraycpy.body");
270 auto DoneBB = createBasicBlock("omp.arraycpy.done");
271 auto IsEmpty =
272 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
273 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000274
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 // Enter the loop body, making that address the current address.
276 auto EntryBB = Builder.GetInsertBlock();
277 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000278
279 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
280
281 llvm::PHINode *SrcElementPHI =
282 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
283 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
284 Address SrcElementCurrent =
285 Address(SrcElementPHI,
286 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
287
288 llvm::PHINode *DestElementPHI =
289 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
290 DestElementPHI->addIncoming(DestBegin, EntryBB);
291 Address DestElementCurrent =
292 Address(DestElementPHI,
293 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000294
Alexey Bataev420d45b2015-04-14 05:11:24 +0000295 // Emit copy.
296 CopyGen(DestElementCurrent, SrcElementCurrent);
297
298 // Shift the address forward by one element.
299 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000300 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000301 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000302 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000303 // Check whether we've reached the end.
304 auto Done =
305 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
306 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000307 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
308 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000309
310 // Done.
311 EmitBlock(DoneBB, /*IsFinished=*/true);
312}
313
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000314/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000315/// \param DestAddr Address of the array.
316/// \param Type Type of array.
317/// \param Init Initial expression of array.
318static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
319 QualType Type, const Expr *Init) {
320 // Perform element-by-element initialization.
321 QualType ElementTy;
322
323 // Drill down to the base element type on both arrays.
324 auto ArrayTy = Type->getAsArrayTypeUnsafe();
325 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
326 DestAddr =
327 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
328
329 auto DestBegin = DestAddr.getPointer();
330 // Cast from pointer to array type to pointer to single element.
331 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
332 // The basic structure here is a while-do loop.
333 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
334 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
335 auto IsEmpty =
336 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
337 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
338
339 // Enter the loop body, making that address the current address.
340 auto EntryBB = CGF.Builder.GetInsertBlock();
341 CGF.EmitBlock(BodyBB);
342
343 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
344
345 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
346 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
347 DestElementPHI->addIncoming(DestBegin, EntryBB);
348 Address DestElementCurrent =
349 Address(DestElementPHI,
350 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
351
352 // Emit copy.
353 {
354 CodeGenFunction::RunCleanupsScope InitScope(CGF);
355 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
356 /*IsInitializer=*/false);
357 }
358
359 // Shift the address forward by one element.
360 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
361 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
362 // Check whether we've reached the end.
363 auto Done =
364 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
365 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
366 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
367
368 // Done.
369 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
370}
371
John McCall7f416cc2015-09-08 08:05:57 +0000372void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
373 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000374 const VarDecl *SrcVD, const Expr *Copy) {
375 if (OriginalType->isArrayType()) {
376 auto *BO = dyn_cast<BinaryOperator>(Copy);
377 if (BO && BO->getOpcode() == BO_Assign) {
378 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000379 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000380 } else {
381 // For arrays with complex element types perform element by element
382 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000383 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000384 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000385 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000386 // Working with the single array element, so have to remap
387 // destination and source variables to corresponding array
388 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000389 CodeGenFunction::OMPPrivateScope Remap(*this);
390 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000391 return DestElement;
392 });
393 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000394 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000395 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000396 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000397 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000398 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000399 } else {
400 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000401 CodeGenFunction::OMPPrivateScope Remap(*this);
402 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
403 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000404 (void)Remap.Privatize();
405 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000406 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000407 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000408}
409
Alexey Bataev69c62a92015-04-15 04:52:20 +0000410bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
411 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000412 if (!HaveInsertPoint())
413 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000414 bool FirstprivateIsLastprivate = false;
415 llvm::DenseSet<const VarDecl *> Lastprivates;
416 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
417 for (const auto *D : C->varlists())
418 Lastprivates.insert(
419 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
420 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000421 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000422 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000423 auto IRef = C->varlist_begin();
424 auto InitsRef = C->inits().begin();
425 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000426 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000427 FirstprivateIsLastprivate =
428 FirstprivateIsLastprivate ||
429 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
430 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000431 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
432 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
433 bool IsRegistered;
434 DeclRefExpr DRE(
435 const_cast<VarDecl *>(OrigVD),
436 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
437 OrigVD) != nullptr,
438 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000439 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000440 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000441 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000442 // Emit VarDecl with copy init for arrays.
443 // Get the address of the original variable captured in current
444 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000445 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000446 auto Emission = EmitAutoVarAlloca(*VD);
447 auto *Init = VD->getInit();
448 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
449 // Perform simple memcpy.
450 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000451 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000452 } else {
453 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000454 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000455 [this, VDInit, Init](Address DestElement,
456 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000457 // Clean up any temporaries needed by the initialization.
458 RunCleanupsScope InitScope(*this);
459 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000460 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000461 EmitAnyExprToMem(Init, DestElement,
462 Init->getType().getQualifiers(),
463 /*IsInitializer*/ false);
464 LocalDeclMap.erase(VDInit);
465 });
466 }
467 EmitAutoVarCleanups(Emission);
468 return Emission.getAllocatedAddress();
469 });
470 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000471 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000472 // Emit private VarDecl with copy init.
473 // Remap temp VDInit variable to the address of the original
474 // variable
475 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000476 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 EmitDecl(*VD);
478 LocalDeclMap.erase(VDInit);
479 return GetAddrOfLocalVar(VD);
480 });
481 }
482 assert(IsRegistered &&
483 "firstprivate var already registered as private");
484 // Silence the warning about unused variable.
485 (void)IsRegistered;
486 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000487 ++IRef;
488 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000489 }
490 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000491 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000492}
493
Alexey Bataev03b340a2014-10-21 03:16:40 +0000494void CodeGenFunction::EmitOMPPrivateClause(
495 const OMPExecutableDirective &D,
496 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000497 if (!HaveInsertPoint())
498 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000499 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000500 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000501 auto IRef = C->varlist_begin();
502 for (auto IInit : C->private_copies()) {
503 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000504 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
505 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
506 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000507 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000508 // Emit private VarDecl with copy init.
509 EmitDecl(*VD);
510 return GetAddrOfLocalVar(VD);
511 });
512 assert(IsRegistered && "private var already registered as private");
513 // Silence the warning about unused variable.
514 (void)IsRegistered;
515 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000516 ++IRef;
517 }
518 }
519}
520
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000521bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000522 if (!HaveInsertPoint())
523 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000524 // threadprivate_var1 = master_threadprivate_var1;
525 // operator=(threadprivate_var2, master_threadprivate_var2);
526 // ...
527 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 llvm::DenseSet<const VarDecl *> CopiedVars;
529 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000530 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000531 auto IRef = C->varlist_begin();
532 auto ISrcRef = C->source_exprs().begin();
533 auto IDestRef = C->destination_exprs().begin();
534 for (auto *AssignOp : C->assignment_ops()) {
535 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000536 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000537 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000538 // Get the address of the master variable. If we are emitting code with
539 // TLS support, the address is passed from the master as field in the
540 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000541 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000542 if (getLangOpts().OpenMPUseTLS &&
543 getContext().getTargetInfo().isTLSSupported()) {
544 assert(CapturedStmtInfo->lookup(VD) &&
545 "Copyin threadprivates should have been captured!");
546 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
547 VK_LValue, (*IRef)->getExprLoc());
548 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000549 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000550 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000551 MasterAddr =
552 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
553 : CGM.GetAddrOfGlobal(VD),
554 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000555 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000556 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000557 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000558 if (CopiedVars.size() == 1) {
559 // At first check if current thread is a master thread. If it is, no
560 // need to copy data.
561 CopyBegin = createBasicBlock("copyin.not.master");
562 CopyEnd = createBasicBlock("copyin.not.master.end");
563 Builder.CreateCondBr(
564 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000565 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
566 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000567 CopyBegin, CopyEnd);
568 EmitBlock(CopyBegin);
569 }
570 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
571 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000572 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000573 }
574 ++IRef;
575 ++ISrcRef;
576 ++IDestRef;
577 }
578 }
579 if (CopyEnd) {
580 // Exit out of copying procedure for non-master thread.
581 EmitBlock(CopyEnd, /*IsFinished=*/true);
582 return true;
583 }
584 return false;
585}
586
Alexey Bataev38e89532015-04-16 04:54:05 +0000587bool CodeGenFunction::EmitOMPLastprivateClauseInit(
588 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000589 if (!HaveInsertPoint())
590 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000591 bool HasAtLeastOneLastprivate = false;
592 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000593 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000594 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000595 auto IRef = C->varlist_begin();
596 auto IDestRef = C->destination_exprs().begin();
597 for (auto *IInit : C->private_copies()) {
598 // Keep the address of the original variable for future update at the end
599 // of the loop.
600 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
601 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
602 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000603 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000604 DeclRefExpr DRE(
605 const_cast<VarDecl *>(OrigVD),
606 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
607 OrigVD) != nullptr,
608 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
609 return EmitLValue(&DRE).getAddress();
610 });
611 // Check if the variable is also a firstprivate: in this case IInit is
612 // not generated. Initialization of this variable will happen in codegen
613 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000614 if (IInit) {
615 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
616 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000617 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000618 // Emit private VarDecl with copy init.
619 EmitDecl(*VD);
620 return GetAddrOfLocalVar(VD);
621 });
622 assert(IsRegistered &&
623 "lastprivate var already registered as private");
624 (void)IsRegistered;
625 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000626 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000627 ++IRef;
628 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000629 }
630 }
631 return HasAtLeastOneLastprivate;
632}
633
634void CodeGenFunction::EmitOMPLastprivateClauseFinal(
635 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000636 if (!HaveInsertPoint())
637 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000638 // Emit following code:
639 // if (<IsLastIterCond>) {
640 // orig_var1 = private_orig_var1;
641 // ...
642 // orig_varn = private_orig_varn;
643 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000644 llvm::BasicBlock *ThenBB = nullptr;
645 llvm::BasicBlock *DoneBB = nullptr;
646 if (IsLastIterCond) {
647 ThenBB = createBasicBlock(".omp.lastprivate.then");
648 DoneBB = createBasicBlock(".omp.lastprivate.done");
649 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
650 EmitBlock(ThenBB);
651 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000652 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000653 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000654 auto IC = LoopDirective->counters().begin();
655 for (auto F : LoopDirective->finals()) {
656 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
657 LoopCountersAndUpdates[D] = F;
658 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000659 }
660 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000661 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
662 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
663 auto IRef = C->varlist_begin();
664 auto ISrcRef = C->source_exprs().begin();
665 auto IDestRef = C->destination_exprs().begin();
666 for (auto *AssignOp : C->assignment_ops()) {
667 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
668 QualType Type = PrivateVD->getType();
669 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
670 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
671 // If lastprivate variable is a loop control variable for loop-based
672 // directive, update its value before copyin back to original
673 // variable.
674 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
675 EmitIgnoredExpr(UpExpr);
676 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
677 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
678 // Get the address of the original variable.
679 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
680 // Get the address of the private variable.
681 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
682 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
683 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000684 Address(Builder.CreateLoad(PrivateAddr),
685 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000686 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000687 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000688 ++IRef;
689 ++ISrcRef;
690 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000691 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000692 if (auto *PostUpdate = C->getPostUpdateExpr())
693 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000694 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000695 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000696 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000697}
698
Alexey Bataev31300ed2016-02-04 11:27:03 +0000699static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
700 LValue BaseLV, llvm::Value *Addr) {
701 Address Tmp = Address::invalid();
702 Address TopTmp = Address::invalid();
703 Address MostTopTmp = Address::invalid();
704 BaseTy = BaseTy.getNonReferenceType();
705 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
706 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
707 Tmp = CGF.CreateMemTemp(BaseTy);
708 if (TopTmp.isValid())
709 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
710 else
711 MostTopTmp = Tmp;
712 TopTmp = Tmp;
713 BaseTy = BaseTy->getPointeeType();
714 }
715 llvm::Type *Ty = BaseLV.getPointer()->getType();
716 if (Tmp.isValid())
717 Ty = Tmp.getElementType();
718 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
719 if (Tmp.isValid()) {
720 CGF.Builder.CreateStore(Addr, Tmp);
721 return MostTopTmp;
722 }
723 return Address(Addr, BaseLV.getAlignment());
724}
725
726static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
727 LValue BaseLV) {
728 BaseTy = BaseTy.getNonReferenceType();
729 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
730 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
731 if (auto *PtrTy = BaseTy->getAs<PointerType>())
732 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
733 else {
734 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
735 BaseTy->castAs<ReferenceType>());
736 }
737 BaseTy = BaseTy->getPointeeType();
738 }
739 return CGF.MakeAddrLValue(
740 Address(
741 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
742 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
743 BaseLV.getAlignment()),
744 BaseLV.getType(), BaseLV.getAlignmentSource());
745}
746
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000747void CodeGenFunction::EmitOMPReductionClauseInit(
748 const OMPExecutableDirective &D,
749 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000750 if (!HaveInsertPoint())
751 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000752 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000753 auto ILHS = C->lhs_exprs().begin();
754 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000755 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000756 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000757 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000758 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
759 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
760 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
761 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
762 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
763 Base = TempOASE->getBase()->IgnoreParenImpCasts();
764 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
765 Base = TempASE->getBase()->IgnoreParenImpCasts();
766 auto *DE = cast<DeclRefExpr>(Base);
767 auto *OrigVD = cast<VarDecl>(DE->getDecl());
768 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
769 auto OASELValueUB =
770 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
771 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000772 LValue BaseLValue =
773 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
774 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000775 // Store the address of the original variable associated with the LHS
776 // implicit variable.
777 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
778 return OASELValueLB.getAddress();
779 });
780 // Emit reduction copy.
781 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000782 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
783 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000784 // Emit VarDecl with copy init for arrays.
785 // Get the address of the original variable captured in current
786 // captured region.
787 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
788 OASELValueLB.getPointer());
789 Size = Builder.CreateNUWAdd(
790 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
791 CodeGenFunction::OpaqueValueMapping OpaqueMap(
792 *this, cast<OpaqueValueExpr>(
793 getContext()
794 .getAsVariableArrayType(PrivateVD->getType())
795 ->getSizeExpr()),
796 RValue::get(Size));
797 EmitVariablyModifiedType(PrivateVD->getType());
798 auto Emission = EmitAutoVarAlloca(*PrivateVD);
799 auto Addr = Emission.getAllocatedAddress();
800 auto *Init = PrivateVD->getInit();
801 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
802 EmitAutoVarCleanups(Emission);
803 // Emit private VarDecl with reduction init.
804 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
805 OASELValueLB.getPointer());
806 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000807 return castToBase(*this, OrigVD->getType(),
808 OASELValueLB.getType(), OriginalBaseLValue,
809 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000810 });
811 assert(IsRegistered && "private var already registered as private");
812 // Silence the warning about unused variable.
813 (void)IsRegistered;
814 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
815 return GetAddrOfLocalVar(PrivateVD);
816 });
817 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
818 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
819 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
820 Base = TempASE->getBase()->IgnoreParenImpCasts();
821 auto *DE = cast<DeclRefExpr>(Base);
822 auto *OrigVD = cast<VarDecl>(DE->getDecl());
823 auto ASELValue = EmitLValue(ASE);
824 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000825 LValue BaseLValue = loadToBegin(
826 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000827 // Store the address of the original variable associated with the LHS
828 // implicit variable.
829 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
830 return ASELValue.getAddress();
831 });
832 // Emit reduction copy.
833 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000834 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000835 OriginalBaseLValue]() -> Address {
836 // Emit private VarDecl with reduction init.
837 EmitDecl(*PrivateVD);
838 auto Addr = GetAddrOfLocalVar(PrivateVD);
839 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
840 ASELValue.getPointer());
841 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000842 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
843 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000844 });
845 assert(IsRegistered && "private var already registered as private");
846 // Silence the warning about unused variable.
847 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000848 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
849 return Builder.CreateElementBitCast(
850 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
851 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000852 });
853 } else {
854 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000855 QualType Type = PrivateVD->getType();
856 if (getContext().getAsArrayType(Type)) {
857 // Store the address of the original variable associated with the LHS
858 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000859 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
860 CapturedStmtInfo->lookup(OrigVD) != nullptr,
861 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000862 Address OriginalAddr = EmitLValue(&DRE).getAddress();
863 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
864 LHSVD]() -> Address {
865 return Builder.CreateElementBitCast(
866 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
867 "lhs.begin");
868 });
869 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
870 if (Type->isVariablyModifiedType()) {
871 CodeGenFunction::OpaqueValueMapping OpaqueMap(
872 *this, cast<OpaqueValueExpr>(
873 getContext()
874 .getAsVariableArrayType(PrivateVD->getType())
875 ->getSizeExpr()),
876 RValue::get(
877 getTypeSize(OrigVD->getType().getNonReferenceType())));
878 EmitVariablyModifiedType(Type);
879 }
880 auto Emission = EmitAutoVarAlloca(*PrivateVD);
881 auto Addr = Emission.getAllocatedAddress();
882 auto *Init = PrivateVD->getInit();
883 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
884 EmitAutoVarCleanups(Emission);
885 return Emission.getAllocatedAddress();
886 });
887 assert(IsRegistered && "private var already registered as private");
888 // Silence the warning about unused variable.
889 (void)IsRegistered;
890 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
891 return Builder.CreateElementBitCast(
892 GetAddrOfLocalVar(PrivateVD),
893 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
894 });
895 } else {
896 // Store the address of the original variable associated with the LHS
897 // implicit variable.
898 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
899 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
900 CapturedStmtInfo->lookup(OrigVD) != nullptr,
901 IRef->getType(), VK_LValue, IRef->getExprLoc());
902 return EmitLValue(&DRE).getAddress();
903 });
904 // Emit reduction copy.
905 bool IsRegistered =
906 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
907 // Emit private VarDecl with reduction init.
908 EmitDecl(*PrivateVD);
909 return GetAddrOfLocalVar(PrivateVD);
910 });
911 assert(IsRegistered && "private var already registered as private");
912 // Silence the warning about unused variable.
913 (void)IsRegistered;
914 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
915 return GetAddrOfLocalVar(PrivateVD);
916 });
917 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000918 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000919 ++ILHS;
920 ++IRHS;
921 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000922 }
923 }
924}
925
926void CodeGenFunction::EmitOMPReductionClauseFinal(
927 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000928 if (!HaveInsertPoint())
929 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000930 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000931 llvm::SmallVector<const Expr *, 8> LHSExprs;
932 llvm::SmallVector<const Expr *, 8> RHSExprs;
933 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000934 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000935 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000936 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000937 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000938 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
939 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
940 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
941 }
942 if (HasAtLeastOneReduction) {
943 // Emit nowait reduction if nowait clause is present or directive is a
944 // parallel directive (it always has implicit barrier).
945 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000946 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000947 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000948 isOpenMPParallelDirective(D.getDirectiveKind()) ||
949 D.getDirectiveKind() == OMPD_simd,
950 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000951 }
952}
953
Alexey Bataev61205072016-03-02 04:57:40 +0000954static void emitPostUpdateForReductionClause(
955 CodeGenFunction &CGF, const OMPExecutableDirective &D,
956 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
957 if (!CGF.HaveInsertPoint())
958 return;
959 llvm::BasicBlock *DoneBB = nullptr;
960 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
961 if (auto *PostUpdate = C->getPostUpdateExpr()) {
962 if (!DoneBB) {
963 if (auto *Cond = CondGen(CGF)) {
964 // If the first post-update expression is found, emit conditional
965 // block if it was requested.
966 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
967 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
968 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
969 CGF.EmitBlock(ThenBB);
970 }
971 }
972 CGF.EmitIgnoredExpr(PostUpdate);
973 }
974 }
975 if (DoneBB)
976 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
977}
978
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000979static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
980 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000981 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000982 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000983 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000984 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
985 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000986 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000987 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000988 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000989 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000990 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
991 /*IgnoreResultAssign*/ true);
992 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
993 CGF, NumThreads, NumThreadsClause->getLocStart());
994 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000995 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000996 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000997 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
998 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
999 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001000 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001001 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1002 if (C->getNameModifier() == OMPD_unknown ||
1003 C->getNameModifier() == OMPD_parallel) {
1004 IfCond = C->getCondition();
1005 break;
1006 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001007 }
1008 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001009 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001010}
1011
1012void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001013 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001014 // Emit parallel region as a standalone region.
1015 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1016 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001017 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001018 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1019 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001020 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001021 // propagation master's thread values of threadprivate variables to local
1022 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001023 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1024 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1025 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001026 }
1027 CGF.EmitOMPPrivateClause(S, PrivateScope);
1028 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1029 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001030 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001031 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001032 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001033 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001034 emitPostUpdateForReductionClause(
1035 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001036}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001037
Alexey Bataev0f34da12015-07-02 04:17:07 +00001038void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1039 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001040 RunCleanupsScope BodyScope(*this);
1041 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001042 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001043 EmitIgnoredExpr(I);
1044 }
Alexander Musman3276a272015-03-21 10:12:56 +00001045 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001046 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001047 for (auto U : C->updates()) {
1048 EmitIgnoredExpr(U);
1049 }
1050 }
1051
Alexander Musmana5f070a2014-10-01 06:03:56 +00001052 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001053 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001054 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001055 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001056 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001057 // The end (updates/cleanups).
1058 EmitBlock(Continue.getBlock());
1059 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001060}
1061
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001062void CodeGenFunction::EmitOMPInnerLoop(
1063 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1064 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001065 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1066 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001067 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001068
1069 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001070 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001071 EmitBlock(CondBlock);
1072 LoopStack.push(CondBlock);
1073
1074 // If there are any cleanups between here and the loop-exit scope,
1075 // create a block to stage a loop exit along.
1076 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001077 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001078 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001079
Alexander Musmand196ef22014-10-07 08:57:09 +00001080 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001081
Alexey Bataev2df54a02015-03-12 08:53:29 +00001082 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001083 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001084 if (ExitBlock != LoopExit.getBlock()) {
1085 EmitBlock(ExitBlock);
1086 EmitBranchThroughCleanup(LoopExit);
1087 }
1088
1089 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001090 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001091
1092 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001093 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001094 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1095
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001096 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001097
1098 // Emit "IV = IV + 1" and a back-edge to the condition block.
1099 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001100 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001101 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001102 BreakContinueStack.pop_back();
1103 EmitBranch(CondBlock);
1104 LoopStack.pop();
1105 // Emit the fall-through block.
1106 EmitBlock(LoopExit.getBlock());
1107}
1108
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001109void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001110 if (!HaveInsertPoint())
1111 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001112 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001113 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001114 for (auto Init : C->inits()) {
1115 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001116 auto *OrigVD = cast<VarDecl>(
1117 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1118 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1119 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1120 VD->getInit()->getType(), VK_LValue,
1121 VD->getInit()->getExprLoc());
1122 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1123 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001124 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001125 /*capturedByInit=*/false);
1126 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001127 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001128 // Emit the linear steps for the linear clauses.
1129 // If a step is not constant, it is pre-calculated before the loop.
1130 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1131 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001132 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001133 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001134 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001135 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001136 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001137}
1138
1139static void emitLinearClauseFinal(CodeGenFunction &CGF,
1140 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001141 if (!CGF.HaveInsertPoint())
1142 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001143 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001144 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001145 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001146 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001147 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1148 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001149 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001150 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001151 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001152 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001153 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001154 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001155 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001156 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001157 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001158 }
1159 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001160}
1161
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001162static void emitAlignedClause(CodeGenFunction &CGF,
1163 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001164 if (!CGF.HaveInsertPoint())
1165 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001166 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001167 unsigned ClauseAlignment = 0;
1168 if (auto AlignmentExpr = Clause->getAlignment()) {
1169 auto AlignmentCI =
1170 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1171 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001172 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001173 for (auto E : Clause->varlists()) {
1174 unsigned Alignment = ClauseAlignment;
1175 if (Alignment == 0) {
1176 // OpenMP [2.8.1, Description]
1177 // If no optional parameter is specified, implementation-defined default
1178 // alignments for SIMD instructions on the target platforms are assumed.
1179 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001180 CGF.getContext()
1181 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1182 E->getType()->getPointeeType()))
1183 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001184 }
1185 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1186 "alignment is not power of 2");
1187 if (Alignment != 0) {
1188 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1189 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1190 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001191 }
1192 }
1193}
1194
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001195static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001196 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001197 ArrayRef<Expr *> Counters,
1198 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001199 if (!CGF.HaveInsertPoint())
1200 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001201 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001202 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001203 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1204 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001205 Address Addr = Address::invalid();
1206 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001207 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001208 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001209 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001210 Addr = VarEmission.getAllocatedAddress();
1211 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001212 });
John McCall7f416cc2015-09-08 08:05:57 +00001213 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001214 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001215 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001216}
1217
Alexey Bataev62dbb972015-04-22 11:59:37 +00001218static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1219 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1220 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001221 if (!CGF.HaveInsertPoint())
1222 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001223 {
1224 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001225 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1226 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001227 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001228 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001229 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001230 CGF.EmitIgnoredExpr(I);
1231 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001232 }
1233 // Check that loop is executed at least one time.
1234 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1235}
1236
Alexander Musman3276a272015-03-21 10:12:56 +00001237static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001238emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001239 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001240 if (!CGF.HaveInsertPoint())
1241 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001242 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001243 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001244 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001245 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1246 auto *PrivateVD =
1247 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001248 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001249 // Emit private VarDecl with copy init.
1250 CGF.EmitVarDecl(*PrivateVD);
1251 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001252 });
1253 assert(IsRegistered && "linear var already registered as private");
1254 // Silence the warning about unused variable.
1255 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001256 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001257 }
1258 }
1259}
1260
Alexey Bataev45bfad52015-08-21 12:19:04 +00001261static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001262 const OMPExecutableDirective &D,
1263 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001264 if (!CGF.HaveInsertPoint())
1265 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001266 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001267 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1268 /*ignoreResult=*/true);
1269 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1270 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1271 // In presence of finite 'safelen', it may be unsafe to mark all
1272 // the memory instructions parallel, because loop-carried
1273 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001274 if (!IsMonotonic)
1275 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001276 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001277 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1278 /*ignoreResult=*/true);
1279 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001280 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001281 // In presence of finite 'safelen', it may be unsafe to mark all
1282 // the memory instructions parallel, because loop-carried
1283 // dependences of 'safelen' iterations are possible.
1284 CGF.LoopStack.setParallel(false);
1285 }
1286}
1287
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001288void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1289 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001290 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001291 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001292 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001293 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001294}
1295
1296void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001297 if (!HaveInsertPoint())
1298 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001299 auto IC = D.counters().begin();
1300 for (auto F : D.finals()) {
1301 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001302 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001303 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1304 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1305 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001306 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001307 OMPPrivateScope VarScope(*this);
1308 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001309 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001310 (void)VarScope.Privatize();
1311 EmitIgnoredExpr(F);
1312 }
1313 ++IC;
1314 }
1315 emitLinearClauseFinal(*this, D);
1316}
1317
Alexander Musman515ad8c2014-05-22 08:54:05 +00001318void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001319 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001320 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001321 // for (IV in 0..LastIteration) BODY;
1322 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001323 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001324 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001325
Alexey Bataev62dbb972015-04-22 11:59:37 +00001326 // Emit: if (PreCond) - begin.
1327 // If the condition constant folds and can be elided, avoid emitting the
1328 // whole loop.
1329 bool CondConstant;
1330 llvm::BasicBlock *ContBlock = nullptr;
1331 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1332 if (!CondConstant)
1333 return;
1334 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001335 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1336 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001337 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1338 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001339 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001340 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001341 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001342
1343 // Emit the loop iteration variable.
1344 const Expr *IVExpr = S.getIterationVariable();
1345 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1346 CGF.EmitVarDecl(*IVDecl);
1347 CGF.EmitIgnoredExpr(S.getInit());
1348
1349 // Emit the iterations count variable.
1350 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001351 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001352 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1353 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1354 // Emit calculation of the iterations count.
1355 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001356 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001357
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001358 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001359
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001360 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001361 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001362 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001363 {
1364 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001365 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1366 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001367 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001368 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001369 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001370 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001371 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001372 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1373 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001374 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001375 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001376 CGF.EmitStopPoint(&S);
1377 },
1378 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001379 // Emit final copy of the lastprivate variables at the end of loops.
1380 if (HasLastprivateClause) {
1381 CGF.EmitOMPLastprivateClauseFinal(S);
1382 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001383 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001384 emitPostUpdateForReductionClause(
1385 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001386 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001387 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001388 // Emit: if (PreCond) - end.
1389 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001390 CGF.EmitBranch(ContBlock);
1391 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001392 }
1393 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001394 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001395}
1396
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001397void CodeGenFunction::EmitOMPForOuterLoop(
1398 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1399 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1400 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001401 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001402
1403 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001404 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001405
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001406 assert((Ordered ||
1407 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001408 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001409
1410 // Emit outer loop.
1411 //
1412 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001413 // When schedule(dynamic,chunk_size) is specified, the iterations are
1414 // distributed to threads in the team in chunks as the threads request them.
1415 // Each thread executes a chunk of iterations, then requests another chunk,
1416 // until no chunks remain to be distributed. Each chunk contains chunk_size
1417 // iterations, except for the last chunk to be distributed, which may have
1418 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1419 //
1420 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1421 // to threads in the team in chunks as the executing threads request them.
1422 // Each thread executes a chunk of iterations, then requests another chunk,
1423 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1424 // each chunk is proportional to the number of unassigned iterations divided
1425 // by the number of threads in the team, decreasing to 1. For a chunk_size
1426 // with value k (greater than 1), the size of each chunk is determined in the
1427 // same way, with the restriction that the chunks do not contain fewer than k
1428 // iterations (except for the last chunk to be assigned, which may have fewer
1429 // than k iterations).
1430 //
1431 // When schedule(auto) is specified, the decision regarding scheduling is
1432 // delegated to the compiler and/or runtime system. The programmer gives the
1433 // implementation the freedom to choose any possible mapping of iterations to
1434 // threads in the team.
1435 //
1436 // When schedule(runtime) is specified, the decision regarding scheduling is
1437 // deferred until run time, and the schedule and chunk size are taken from the
1438 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1439 // implementation defined
1440 //
1441 // while(__kmpc_dispatch_next(&LB, &UB)) {
1442 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001443 // while (idx <= UB) { BODY; ++idx;
1444 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1445 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001446 // }
1447 //
1448 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001449 // When schedule(static, chunk_size) is specified, iterations are divided into
1450 // chunks of size chunk_size, and the chunks are assigned to the threads in
1451 // the team in a round-robin fashion in the order of the thread number.
1452 //
1453 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1454 // while (idx <= UB) { BODY; ++idx; } // inner loop
1455 // LB = LB + ST;
1456 // UB = UB + ST;
1457 // }
1458 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001459
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001460 const Expr *IVExpr = S.getIterationVariable();
1461 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1462 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1463
John McCall7f416cc2015-09-08 08:05:57 +00001464 if (DynamicOrOrdered) {
1465 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1466 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1467 IVSize, IVSigned, Ordered, UBVal, Chunk);
1468 } else {
1469 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1470 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1471 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001472
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001473 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1474
1475 // Start the loop with a block that tests the condition.
1476 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1477 EmitBlock(CondBlock);
1478 LoopStack.push(CondBlock);
1479
1480 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001481 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001482 // UB = min(UB, GlobalUB)
1483 EmitIgnoredExpr(S.getEnsureUpperBound());
1484 // IV = LB
1485 EmitIgnoredExpr(S.getInit());
1486 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001487 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001488 } else {
1489 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1490 IL, LB, UB, ST);
1491 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001492
1493 // If there are any cleanups between here and the loop-exit scope,
1494 // create a block to stage a loop exit along.
1495 auto ExitBlock = LoopExit.getBlock();
1496 if (LoopScope.requiresCleanups())
1497 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1498
1499 auto LoopBody = createBasicBlock("omp.dispatch.body");
1500 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1501 if (ExitBlock != LoopExit.getBlock()) {
1502 EmitBlock(ExitBlock);
1503 EmitBranchThroughCleanup(LoopExit);
1504 }
1505 EmitBlock(LoopBody);
1506
Alexander Musman92bdaab2015-03-12 13:37:50 +00001507 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1508 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001509 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001510 EmitIgnoredExpr(S.getInit());
1511
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001512 // Create a block for the increment.
1513 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1514 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1515
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001516 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1517 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001518 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1519 LoopStack.setParallel(!IsMonotonic);
1520 else
1521 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001522
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001523 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001524 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1525 [&S, LoopExit](CodeGenFunction &CGF) {
1526 CGF.EmitOMPLoopBody(S, LoopExit);
1527 CGF.EmitStopPoint(&S);
1528 },
1529 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1530 if (Ordered) {
1531 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1532 CGF, Loc, IVSize, IVSigned);
1533 }
1534 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001535
1536 EmitBlock(Continue.getBlock());
1537 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001538 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001539 // Emit "LB = LB + Stride", "UB = UB + Stride".
1540 EmitIgnoredExpr(S.getNextLowerBound());
1541 EmitIgnoredExpr(S.getNextUpperBound());
1542 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001543
1544 EmitBranch(CondBlock);
1545 LoopStack.pop();
1546 // Emit the fall-through block.
1547 EmitBlock(LoopExit.getBlock());
1548
1549 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001550 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001551 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001552}
1553
Alexander Musmanc6388682014-12-15 07:07:06 +00001554/// \brief Emit a helper variable and return corresponding lvalue.
1555static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1556 const DeclRefExpr *Helper) {
1557 auto VDecl = cast<VarDecl>(Helper->getDecl());
1558 CGF.EmitVarDecl(*VDecl);
1559 return CGF.EmitLValue(Helper);
1560}
1561
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001562namespace {
1563 struct ScheduleKindModifiersTy {
1564 OpenMPScheduleClauseKind Kind;
1565 OpenMPScheduleClauseModifier M1;
1566 OpenMPScheduleClauseModifier M2;
1567 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1568 OpenMPScheduleClauseModifier M1,
1569 OpenMPScheduleClauseModifier M2)
1570 : Kind(Kind), M1(M1), M2(M2) {}
1571 };
1572} // namespace
1573
Alexey Bataev38e89532015-04-16 04:54:05 +00001574bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001575 // Emit the loop iteration variable.
1576 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1577 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1578 EmitVarDecl(*IVDecl);
1579
1580 // Emit the iterations count variable.
1581 // If it is not a variable, Sema decided to calculate iterations count on each
1582 // iteration (e.g., it is foldable into a constant).
1583 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1584 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1585 // Emit calculation of the iterations count.
1586 EmitIgnoredExpr(S.getCalcLastIteration());
1587 }
1588
1589 auto &RT = CGM.getOpenMPRuntime();
1590
Alexey Bataev38e89532015-04-16 04:54:05 +00001591 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001592 // Check pre-condition.
1593 {
1594 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001595 // If the condition constant folds and can be elided, avoid emitting the
1596 // whole loop.
1597 bool CondConstant;
1598 llvm::BasicBlock *ContBlock = nullptr;
1599 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1600 if (!CondConstant)
1601 return false;
1602 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001603 auto *ThenBlock = createBasicBlock("omp.precond.then");
1604 ContBlock = createBasicBlock("omp.precond.end");
1605 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001606 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001607 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001608 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001609 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001610
1611 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001612 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001613 // Emit 'then' code.
1614 {
1615 // Emit helper vars inits.
1616 LValue LB =
1617 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1618 LValue UB =
1619 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1620 LValue ST =
1621 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1622 LValue IL =
1623 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1624
1625 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001626 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1627 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001628 // initialization of firstprivate variables and post-update of
1629 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001630 CGM.getOpenMPRuntime().emitBarrierCall(
1631 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1632 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001633 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001634 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001635 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001636 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001637 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1638 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001639 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001640 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001641
1642 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001643 llvm::Value *Chunk = nullptr;
1644 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1645 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1646 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1647 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1648 ScheduleKind = C->getScheduleKind();
1649 M1 = C->getFirstScheduleModifier();
1650 M2 = C->getSecondScheduleModifier();
1651 if (const auto *Ch = C->getChunkSize()) {
1652 Chunk = EmitScalarExpr(Ch);
1653 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1654 S.getIterationVariable()->getType(),
1655 S.getLocStart());
1656 }
1657 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001658 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1659 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001660 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001661 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1662 // If the static schedule kind is specified or if the ordered clause is
1663 // specified, and if no monotonic modifier is specified, the effect will
1664 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001665 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001666 /* Chunked */ Chunk != nullptr) &&
1667 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001668 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1669 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001670 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1671 // When no chunk_size is specified, the iteration space is divided into
1672 // chunks that are approximately equal in size, and at most one chunk is
1673 // distributed to each thread. Note that the size of the chunks is
1674 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001675 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1676 IVSize, IVSigned, Ordered,
1677 IL.getAddress(), LB.getAddress(),
1678 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001679 auto LoopExit =
1680 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001681 // UB = min(UB, GlobalUB);
1682 EmitIgnoredExpr(S.getEnsureUpperBound());
1683 // IV = LB;
1684 EmitIgnoredExpr(S.getInit());
1685 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001686 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1687 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001688 [&S, LoopExit](CodeGenFunction &CGF) {
1689 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001690 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001691 },
1692 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001693 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001694 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001695 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001696 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001697 const bool IsMonotonic = Ordered ||
1698 ScheduleKind == OMPC_SCHEDULE_static ||
1699 ScheduleKind == OMPC_SCHEDULE_unknown ||
1700 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1701 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001702 // Emit the outer loop, which requests its work chunk [LB..UB] from
1703 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001704 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001705 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1706 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001707 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001708 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001709 // Emit post-update of the reduction variables if IsLastIter != 0.
1710 emitPostUpdateForReductionClause(
1711 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1712 return CGF.Builder.CreateIsNotNull(
1713 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1714 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001715 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1716 if (HasLastprivateClause)
1717 EmitOMPLastprivateClauseFinal(
1718 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001719 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001720 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1721 EmitOMPSimdFinal(S);
1722 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001723 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001724 if (ContBlock) {
1725 EmitBranch(ContBlock);
1726 EmitBlock(ContBlock, true);
1727 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001728 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001729 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001730}
1731
1732void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001733 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001734 {
1735 OMPLexicalScope Scope(*this, S);
1736 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1737 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1738 };
1739 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1740 S.hasCancel());
1741 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001742
1743 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001744 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001745 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1746 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001747}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001748
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001749void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001750 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001751 {
1752 OMPLexicalScope Scope(*this, S);
1753 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1754 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1755 };
1756 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1757 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001758
1759 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001760 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001761 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1762 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001763}
1764
Alexey Bataev2df54a02015-03-12 08:53:29 +00001765static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1766 const Twine &Name,
1767 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001768 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001769 if (Init)
1770 CGF.EmitScalarInit(Init, LVal);
1771 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001772}
1773
Alexey Bataev3392d762016-02-16 11:18:12 +00001774void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001775 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1776 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001777 bool HasLastprivates = false;
1778 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1779 auto &C = CGF.CGM.getContext();
1780 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1781 // Emit helper vars inits.
1782 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1783 CGF.Builder.getInt32(0));
1784 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1785 : CGF.Builder.getInt32(0);
1786 LValue UB =
1787 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1788 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1789 CGF.Builder.getInt32(1));
1790 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1791 CGF.Builder.getInt32(0));
1792 // Loop counter.
1793 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1794 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1795 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1796 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1797 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1798 // Generate condition for loop.
1799 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1800 OK_Ordinary, S.getLocStart(),
1801 /*fpContractable=*/false);
1802 // Increment for loop counter.
1803 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1804 S.getLocStart());
1805 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1806 // Iterate through all sections and emit a switch construct:
1807 // switch (IV) {
1808 // case 0:
1809 // <SectionStmt[0]>;
1810 // break;
1811 // ...
1812 // case <NumSection> - 1:
1813 // <SectionStmt[<NumSection> - 1]>;
1814 // break;
1815 // }
1816 // .omp.sections.exit:
1817 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1818 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1819 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1820 CS == nullptr ? 1 : CS->size());
1821 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001822 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001823 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001824 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1825 CGF.EmitBlock(CaseBB);
1826 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001827 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001828 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001829 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001830 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001831 } else {
1832 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1833 CGF.EmitBlock(CaseBB);
1834 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1835 CGF.EmitStmt(Stmt);
1836 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001837 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001838 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001839 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001840
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001841 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1842 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001843 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001844 // initialization of firstprivate variables and post-update of lastprivate
1845 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001846 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1847 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1848 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001849 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001850 CGF.EmitOMPPrivateClause(S, LoopScope);
1851 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1852 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1853 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001854
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001855 // Emit static non-chunked loop.
1856 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1857 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1858 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1859 UB.getAddress(), ST.getAddress());
1860 // UB = min(UB, GlobalUB);
1861 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1862 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1863 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1864 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1865 // IV = LB;
1866 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1867 // while (idx <= UB) { BODY; ++idx; }
1868 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1869 [](CodeGenFunction &) {});
1870 // Tell the runtime we are done.
1871 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1872 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001873 // Emit post-update of the reduction variables if IsLastIter != 0.
1874 emitPostUpdateForReductionClause(
1875 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1876 return CGF.Builder.CreateIsNotNull(
1877 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1878 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001879
1880 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1881 if (HasLastprivates)
1882 CGF.EmitOMPLastprivateClauseFinal(
1883 S, CGF.Builder.CreateIsNotNull(
1884 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001885 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001886
1887 bool HasCancel = false;
1888 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1889 HasCancel = OSD->hasCancel();
1890 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1891 HasCancel = OPSD->hasCancel();
1892 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1893 HasCancel);
1894 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1895 // clause. Otherwise the barrier will be generated by the codegen for the
1896 // directive.
1897 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001898 // Emit implicit barrier to synchronize threads and avoid data races on
1899 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001900 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1901 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001902 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001903}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001904
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001905void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001906 {
1907 OMPLexicalScope Scope(*this, S);
1908 EmitSections(S);
1909 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001910 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001911 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001912 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1913 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001914 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001915}
1916
1917void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001918 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001919 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1920 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001921 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001922 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1923 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001924}
1925
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001926void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001927 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001928 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001929 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001930 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001931 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001932 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001933 // Build a list of copyprivate variables along with helper expressions
1934 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001935 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001936 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001937 DestExprs.append(C->destination_exprs().begin(),
1938 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001939 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001940 AssignmentOps.append(C->assignment_ops().begin(),
1941 C->assignment_ops().end());
1942 }
Alexey Bataev3392d762016-02-16 11:18:12 +00001943 {
1944 OMPLexicalScope Scope(*this, S);
1945 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00001946 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001947 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00001948 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00001949 CGF.EmitOMPPrivateClause(S, SingleScope);
1950 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00001951 CGF.EmitStmt(
1952 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1953 };
1954 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1955 CopyprivateVars, DestExprs,
1956 SrcExprs, AssignmentOps);
1957 }
1958 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1959 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00001960 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00001961 CGM.getOpenMPRuntime().emitBarrierCall(
1962 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001963 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001964 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001965}
1966
Alexey Bataev8d690652014-12-04 07:23:53 +00001967void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001968 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001969 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1970 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001971 };
1972 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001973}
1974
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001975void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001976 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001977 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1978 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001979 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00001980 Expr *Hint = nullptr;
1981 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1982 Hint = HintClause->getHint();
1983 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1984 S.getDirectiveName().getAsString(),
1985 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001986}
1987
Alexey Bataev671605e2015-04-13 05:28:11 +00001988void CodeGenFunction::EmitOMPParallelForDirective(
1989 const OMPParallelForDirective &S) {
1990 // Emit directive as a combined directive that consists of two implicit
1991 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00001992 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001993 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1994 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00001995 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001996 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001997}
1998
Alexander Musmane4e893b2014-09-23 09:33:00 +00001999void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002000 const OMPParallelForSimdDirective &S) {
2001 // Emit directive as a combined directive that consists of two implicit
2002 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002003 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002004 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2005 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002006 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002007 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002008}
2009
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002010void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002011 const OMPParallelSectionsDirective &S) {
2012 // Emit directive as a combined directive that consists of two implicit
2013 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002014 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00002015 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002016 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002017}
2018
Alexey Bataev62b63b12015-03-10 07:28:44 +00002019void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2020 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00002021 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002022 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2023 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2024 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002025 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002026 // The first function argument for tasks is a thread id, the second one is a
2027 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002028 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2029 // Get list of private variables.
2030 llvm::SmallVector<const Expr *, 8> PrivateVars;
2031 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002032 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002033 auto IRef = C->varlist_begin();
2034 for (auto *IInit : C->private_copies()) {
2035 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2036 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2037 PrivateVars.push_back(*IRef);
2038 PrivateCopies.push_back(IInit);
2039 }
2040 ++IRef;
2041 }
2042 }
2043 EmittedAsPrivate.clear();
2044 // Get list of firstprivate variables.
2045 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2046 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2047 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002048 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002049 auto IRef = C->varlist_begin();
2050 auto IElemInitRef = C->inits().begin();
2051 for (auto *IInit : C->private_copies()) {
2052 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2053 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2054 FirstprivateVars.push_back(*IRef);
2055 FirstprivateCopies.push_back(IInit);
2056 FirstprivateInits.push_back(*IElemInitRef);
2057 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002058 ++IRef;
2059 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002060 }
2061 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002062 // Build list of dependences.
2063 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2064 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002065 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002066 for (auto *IRef : C->varlists()) {
2067 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2068 }
2069 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002070 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2071 CodeGenFunction &CGF) {
2072 // Set proper addresses for generated private copies.
2073 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2074 OMPPrivateScope Scope(CGF);
2075 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002076 auto *CopyFn = CGF.Builder.CreateLoad(
2077 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2078 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2079 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002080 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002081 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002082 PrivatePtrs;
2083 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2084 CallArgs.push_back(PrivatesPtr);
2085 for (auto *E : PrivateVars) {
2086 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002087 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002088 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2089 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002090 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002091 }
2092 for (auto *E : FirstprivateVars) {
2093 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002094 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002095 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2096 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002097 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002098 }
2099 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2100 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002101 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2102 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002103 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2104 }
2105 }
2106 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002107 if (*PartId) {
2108 // TODO: emit code for untied tasks.
2109 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002110 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002111 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002112 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2113 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002114 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002115 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002116 // Check if the task is final
2117 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002118 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002119 // If the condition constant folds and can be elided, try to avoid emitting
2120 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002121 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002122 bool CondConstant;
2123 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2124 Final.setInt(CondConstant);
2125 else
2126 Final.setPointer(EvaluateExprAsBool(Cond));
2127 } else {
2128 // By default the task is not final.
2129 Final.setInt(/*IntVal=*/false);
2130 }
2131 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002132 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002133 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2134 if (C->getNameModifier() == OMPD_unknown ||
2135 C->getNameModifier() == OMPD_task) {
2136 IfCond = C->getCondition();
2137 break;
2138 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002139 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002140 CGM.getOpenMPRuntime().emitTaskCall(
2141 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002142 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002143 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002144}
2145
Alexey Bataev9f797f32015-02-05 05:57:51 +00002146void CodeGenFunction::EmitOMPTaskyieldDirective(
2147 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002148 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002149}
2150
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002151void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002152 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002153}
2154
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002155void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2156 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002157}
2158
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002159void CodeGenFunction::EmitOMPTaskgroupDirective(
2160 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002161 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002162 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2163 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002164 };
2165 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2166}
2167
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002168void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002169 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002170 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002171 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2172 FlushClause->varlist_end());
2173 }
2174 return llvm::None;
2175 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002176}
2177
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002178void CodeGenFunction::EmitOMPDistributeDirective(
2179 const OMPDistributeDirective &S) {
2180 llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2181}
2182
Alexey Bataev5f600d62015-09-29 03:48:57 +00002183static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2184 const CapturedStmt *S) {
2185 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2186 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2187 CGF.CapturedStmtInfo = &CapStmtInfo;
2188 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2189 Fn->addFnAttr(llvm::Attribute::NoInline);
2190 return Fn;
2191}
2192
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002193void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002194 if (!S.getAssociatedStmt())
2195 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002196 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002197 auto *C = S.getSingleClause<OMPSIMDClause>();
2198 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2199 if (C) {
2200 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2201 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2202 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2203 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2204 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2205 } else {
2206 CGF.EmitStmt(
2207 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2208 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002209 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002210 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002211}
2212
Alexey Bataevb57056f2015-01-22 06:17:56 +00002213static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002214 QualType SrcType, QualType DestType,
2215 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002216 assert(CGF.hasScalarEvaluationKind(DestType) &&
2217 "DestType must have scalar evaluation kind.");
2218 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2219 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002220 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2221 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002222 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002223 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002224}
2225
2226static CodeGenFunction::ComplexPairTy
2227convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002228 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002229 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2230 "DestType must have complex evaluation kind.");
2231 CodeGenFunction::ComplexPairTy ComplexVal;
2232 if (Val.isScalar()) {
2233 // Convert the input element to the element type of the complex.
2234 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002235 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2236 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002237 ComplexVal = CodeGenFunction::ComplexPairTy(
2238 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2239 } else {
2240 assert(Val.isComplex() && "Must be a scalar or complex.");
2241 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2242 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2243 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002244 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002245 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002246 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002247 }
2248 return ComplexVal;
2249}
2250
Alexey Bataev5e018f92015-04-23 06:35:10 +00002251static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2252 LValue LVal, RValue RVal) {
2253 if (LVal.isGlobalReg()) {
2254 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2255 } else {
2256 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2257 : llvm::Monotonic,
2258 LVal.isVolatile(), /*IsInit=*/false);
2259 }
2260}
2261
Alexey Bataev8524d152016-01-21 12:35:58 +00002262void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2263 QualType RValTy, SourceLocation Loc) {
2264 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002265 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002266 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2267 *this, RVal, RValTy, LVal.getType(), Loc)),
2268 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002269 break;
2270 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002271 EmitStoreOfComplex(
2272 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002273 /*isInit=*/false);
2274 break;
2275 case TEK_Aggregate:
2276 llvm_unreachable("Must be a scalar or complex.");
2277 }
2278}
2279
Alexey Bataevb57056f2015-01-22 06:17:56 +00002280static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2281 const Expr *X, const Expr *V,
2282 SourceLocation Loc) {
2283 // v = x;
2284 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2285 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2286 LValue XLValue = CGF.EmitLValue(X);
2287 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002288 RValue Res = XLValue.isGlobalReg()
2289 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2290 : CGF.EmitAtomicLoad(XLValue, Loc,
2291 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002292 : llvm::Monotonic,
2293 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002294 // OpenMP, 2.12.6, atomic Construct
2295 // Any atomic construct with a seq_cst clause forces the atomically
2296 // performed operation to include an implicit flush operation without a
2297 // list.
2298 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002299 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002300 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002301}
2302
Alexey Bataevb8329262015-02-27 06:33:30 +00002303static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2304 const Expr *X, const Expr *E,
2305 SourceLocation Loc) {
2306 // x = expr;
2307 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002308 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002309 // OpenMP, 2.12.6, atomic Construct
2310 // Any atomic construct with a seq_cst clause forces the atomically
2311 // performed operation to include an implicit flush operation without a
2312 // list.
2313 if (IsSeqCst)
2314 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2315}
2316
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002317static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2318 RValue Update,
2319 BinaryOperatorKind BO,
2320 llvm::AtomicOrdering AO,
2321 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002322 auto &Context = CGF.CGM.getContext();
2323 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002324 // expression is simple and atomic is allowed for the given type for the
2325 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002326 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002327 !Update.getScalarVal()->getType()->isIntegerTy() ||
2328 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2329 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002330 X.getAddress().getElementType())) ||
2331 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002332 !Context.getTargetInfo().hasBuiltinAtomic(
2333 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002334 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002335
2336 llvm::AtomicRMWInst::BinOp RMWOp;
2337 switch (BO) {
2338 case BO_Add:
2339 RMWOp = llvm::AtomicRMWInst::Add;
2340 break;
2341 case BO_Sub:
2342 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002343 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002344 RMWOp = llvm::AtomicRMWInst::Sub;
2345 break;
2346 case BO_And:
2347 RMWOp = llvm::AtomicRMWInst::And;
2348 break;
2349 case BO_Or:
2350 RMWOp = llvm::AtomicRMWInst::Or;
2351 break;
2352 case BO_Xor:
2353 RMWOp = llvm::AtomicRMWInst::Xor;
2354 break;
2355 case BO_LT:
2356 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2357 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2358 : llvm::AtomicRMWInst::Max)
2359 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2360 : llvm::AtomicRMWInst::UMax);
2361 break;
2362 case BO_GT:
2363 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2364 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2365 : llvm::AtomicRMWInst::Min)
2366 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2367 : llvm::AtomicRMWInst::UMin);
2368 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002369 case BO_Assign:
2370 RMWOp = llvm::AtomicRMWInst::Xchg;
2371 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002372 case BO_Mul:
2373 case BO_Div:
2374 case BO_Rem:
2375 case BO_Shl:
2376 case BO_Shr:
2377 case BO_LAnd:
2378 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002379 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002380 case BO_PtrMemD:
2381 case BO_PtrMemI:
2382 case BO_LE:
2383 case BO_GE:
2384 case BO_EQ:
2385 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002386 case BO_AddAssign:
2387 case BO_SubAssign:
2388 case BO_AndAssign:
2389 case BO_OrAssign:
2390 case BO_XorAssign:
2391 case BO_MulAssign:
2392 case BO_DivAssign:
2393 case BO_RemAssign:
2394 case BO_ShlAssign:
2395 case BO_ShrAssign:
2396 case BO_Comma:
2397 llvm_unreachable("Unsupported atomic update operation");
2398 }
2399 auto *UpdateVal = Update.getScalarVal();
2400 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2401 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002402 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002403 X.getType()->hasSignedIntegerRepresentation());
2404 }
John McCall7f416cc2015-09-08 08:05:57 +00002405 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002406 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002407}
2408
Alexey Bataev5e018f92015-04-23 06:35:10 +00002409std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002410 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2411 llvm::AtomicOrdering AO, SourceLocation Loc,
2412 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2413 // Update expressions are allowed to have the following forms:
2414 // x binop= expr; -> xrval + expr;
2415 // x++, ++x -> xrval + 1;
2416 // x--, --x -> xrval - 1;
2417 // x = x binop expr; -> xrval binop expr
2418 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002419 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2420 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002421 if (X.isGlobalReg()) {
2422 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2423 // 'xrval'.
2424 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2425 } else {
2426 // Perform compare-and-swap procedure.
2427 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002428 }
2429 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002430 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002431}
2432
2433static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2434 const Expr *X, const Expr *E,
2435 const Expr *UE, bool IsXLHSInRHSPart,
2436 SourceLocation Loc) {
2437 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2438 "Update expr in 'atomic update' must be a binary operator.");
2439 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2440 // Update expressions are allowed to have the following forms:
2441 // x binop= expr; -> xrval + expr;
2442 // x++, ++x -> xrval + 1;
2443 // x--, --x -> xrval - 1;
2444 // x = x binop expr; -> xrval binop expr
2445 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002446 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002447 LValue XLValue = CGF.EmitLValue(X);
2448 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002449 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002450 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2451 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2452 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2453 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2454 auto Gen =
2455 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2456 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2457 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2458 return CGF.EmitAnyExpr(UE);
2459 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002460 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2461 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2462 // OpenMP, 2.12.6, atomic Construct
2463 // Any atomic construct with a seq_cst clause forces the atomically
2464 // performed operation to include an implicit flush operation without a
2465 // list.
2466 if (IsSeqCst)
2467 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2468}
2469
2470static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002471 QualType SourceType, QualType ResType,
2472 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002473 switch (CGF.getEvaluationKind(ResType)) {
2474 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002475 return RValue::get(
2476 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002477 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002478 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002479 return RValue::getComplex(Res.first, Res.second);
2480 }
2481 case TEK_Aggregate:
2482 break;
2483 }
2484 llvm_unreachable("Must be a scalar or complex.");
2485}
2486
2487static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2488 bool IsPostfixUpdate, const Expr *V,
2489 const Expr *X, const Expr *E,
2490 const Expr *UE, bool IsXLHSInRHSPart,
2491 SourceLocation Loc) {
2492 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2493 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2494 RValue NewVVal;
2495 LValue VLValue = CGF.EmitLValue(V);
2496 LValue XLValue = CGF.EmitLValue(X);
2497 RValue ExprRValue = CGF.EmitAnyExpr(E);
2498 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2499 QualType NewVValType;
2500 if (UE) {
2501 // 'x' is updated with some additional value.
2502 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2503 "Update expr in 'atomic capture' must be a binary operator.");
2504 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2505 // Update expressions are allowed to have the following forms:
2506 // x binop= expr; -> xrval + expr;
2507 // x++, ++x -> xrval + 1;
2508 // x--, --x -> xrval - 1;
2509 // x = x binop expr; -> xrval binop expr
2510 // x = expr Op x; - > expr binop xrval;
2511 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2512 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2513 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2514 NewVValType = XRValExpr->getType();
2515 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2516 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2517 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2518 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2519 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2520 RValue Res = CGF.EmitAnyExpr(UE);
2521 NewVVal = IsPostfixUpdate ? XRValue : Res;
2522 return Res;
2523 };
2524 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2525 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2526 if (Res.first) {
2527 // 'atomicrmw' instruction was generated.
2528 if (IsPostfixUpdate) {
2529 // Use old value from 'atomicrmw'.
2530 NewVVal = Res.second;
2531 } else {
2532 // 'atomicrmw' does not provide new value, so evaluate it using old
2533 // value of 'x'.
2534 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2535 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2536 NewVVal = CGF.EmitAnyExpr(UE);
2537 }
2538 }
2539 } else {
2540 // 'x' is simply rewritten with some 'expr'.
2541 NewVValType = X->getType().getNonReferenceType();
2542 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002543 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002544 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2545 NewVVal = XRValue;
2546 return ExprRValue;
2547 };
2548 // Try to perform atomicrmw xchg, otherwise simple exchange.
2549 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2550 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2551 Loc, Gen);
2552 if (Res.first) {
2553 // 'atomicrmw' instruction was generated.
2554 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2555 }
2556 }
2557 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002558 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002559 // OpenMP, 2.12.6, atomic Construct
2560 // Any atomic construct with a seq_cst clause forces the atomically
2561 // performed operation to include an implicit flush operation without a
2562 // list.
2563 if (IsSeqCst)
2564 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2565}
2566
Alexey Bataevb57056f2015-01-22 06:17:56 +00002567static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002568 bool IsSeqCst, bool IsPostfixUpdate,
2569 const Expr *X, const Expr *V, const Expr *E,
2570 const Expr *UE, bool IsXLHSInRHSPart,
2571 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002572 switch (Kind) {
2573 case OMPC_read:
2574 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2575 break;
2576 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002577 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2578 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002579 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002580 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002581 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2582 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002583 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002584 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2585 IsXLHSInRHSPart, Loc);
2586 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002587 case OMPC_if:
2588 case OMPC_final:
2589 case OMPC_num_threads:
2590 case OMPC_private:
2591 case OMPC_firstprivate:
2592 case OMPC_lastprivate:
2593 case OMPC_reduction:
2594 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002595 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002596 case OMPC_collapse:
2597 case OMPC_default:
2598 case OMPC_seq_cst:
2599 case OMPC_shared:
2600 case OMPC_linear:
2601 case OMPC_aligned:
2602 case OMPC_copyin:
2603 case OMPC_copyprivate:
2604 case OMPC_flush:
2605 case OMPC_proc_bind:
2606 case OMPC_schedule:
2607 case OMPC_ordered:
2608 case OMPC_nowait:
2609 case OMPC_untied:
2610 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002611 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002612 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002613 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002614 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002615 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002616 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002617 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002618 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002619 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002620 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002621 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002622 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002623 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002624 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002625 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002626 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2627 }
2628}
2629
2630void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002631 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002632 OpenMPClauseKind Kind = OMPC_unknown;
2633 for (auto *C : S.clauses()) {
2634 // Find first clause (skip seq_cst clause, if it is first).
2635 if (C->getClauseKind() != OMPC_seq_cst) {
2636 Kind = C->getClauseKind();
2637 break;
2638 }
2639 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002640
2641 const auto *CS =
2642 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002643 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002644 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002645 }
2646 // Processing for statements under 'atomic capture'.
2647 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2648 for (const auto *C : Compound->body()) {
2649 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2650 enterFullExpression(EWC);
2651 }
2652 }
2653 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002654
Alexey Bataev3392d762016-02-16 11:18:12 +00002655 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002656 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2657 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002658 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2659 S.getV(), S.getExpr(), S.getUpdateExpr(),
2660 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002661 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002662 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002663}
2664
Samuel Antaobed3c462015-10-02 16:14:20 +00002665void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002666 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002667 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2668
2669 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002670 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002671
Samuel Antaoee8fb302016-01-06 13:42:12 +00002672 llvm::Function *Fn = nullptr;
2673 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002674
2675 // Check if we have any if clause associated with the directive.
2676 const Expr *IfCond = nullptr;
2677
2678 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2679 IfCond = C->getCondition();
2680 }
2681
2682 // Check if we have any device clause associated with the directive.
2683 const Expr *Device = nullptr;
2684 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2685 Device = C->getDevice();
2686 }
2687
Samuel Antaoee8fb302016-01-06 13:42:12 +00002688 // Check if we have an if clause whose conditional always evaluates to false
2689 // or if we do not have any targets specified. If so the target region is not
2690 // an offload entry point.
2691 bool IsOffloadEntry = true;
2692 if (IfCond) {
2693 bool Val;
2694 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2695 IsOffloadEntry = false;
2696 }
2697 if (CGM.getLangOpts().OMPTargetTriples.empty())
2698 IsOffloadEntry = false;
2699
2700 assert(CurFuncDecl && "No parent declaration for target region!");
2701 StringRef ParentName;
2702 // In case we have Ctors/Dtors we use the complete type variant to produce
2703 // the mangling of the device outlined kernel.
2704 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2705 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2706 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2707 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2708 else
2709 ParentName =
2710 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2711
2712 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2713 IsOffloadEntry);
2714
2715 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002716 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002717}
2718
Samuel Antaob68e2db2016-03-03 16:20:23 +00002719void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
2720 OMPLexicalScope Scope(*this, S);
2721 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2722
2723 // FIXME: We should fork teams here instead of just emit the statement.
2724 EmitStmt(CS.getCapturedStmt());
Alexey Bataev13314bf2014-10-09 04:18:56 +00002725}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002726
2727void CodeGenFunction::EmitOMPCancellationPointDirective(
2728 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002729 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2730 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002731}
2732
Alexey Bataev80909872015-07-02 11:25:17 +00002733void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002734 const Expr *IfCond = nullptr;
2735 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2736 if (C->getNameModifier() == OMPD_unknown ||
2737 C->getNameModifier() == OMPD_cancel) {
2738 IfCond = C->getCondition();
2739 break;
2740 }
2741 }
2742 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002743 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002744}
2745
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002746CodeGenFunction::JumpDest
2747CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2748 if (Kind == OMPD_parallel || Kind == OMPD_task)
2749 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002750 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002751 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002752 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002753}
Michael Wong65f367f2015-07-21 13:44:28 +00002754
2755// Generate the instructions for '#pragma omp target data' directive.
2756void CodeGenFunction::EmitOMPTargetDataDirective(
2757 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002758 // emit the code inside the construct for now
2759 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002760 CGM.getOpenMPRuntime().emitInlinedDirective(
2761 *this, OMPD_target_data,
2762 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002763}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002764
Samuel Antaodf67fc42016-01-19 19:15:56 +00002765void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2766 const OMPTargetEnterDataDirective &S) {
2767 // TODO: codegen for target enter data.
2768}
2769
Samuel Antao72590762016-01-19 20:04:50 +00002770void CodeGenFunction::EmitOMPTargetExitDataDirective(
2771 const OMPTargetExitDataDirective &S) {
2772 // TODO: codegen for target exit data.
2773}
2774
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002775void CodeGenFunction::EmitOMPTargetParallelDirective(
2776 const OMPTargetParallelDirective &S) {
2777 // TODO: codegen for target parallel.
2778}
2779
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002780void CodeGenFunction::EmitOMPTargetParallelForDirective(
2781 const OMPTargetParallelForDirective &S) {
2782 // TODO: codegen for target parallel for.
2783}
2784
Alexey Bataev49f6e782015-12-01 04:18:41 +00002785void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2786 // emit the code inside the construct for now
2787 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2788 CGM.getOpenMPRuntime().emitInlinedDirective(
2789 *this, OMPD_taskloop,
2790 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2791}
2792
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002793void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2794 const OMPTaskLoopSimdDirective &S) {
2795 // emit the code inside the construct for now
2796 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2797 CGM.getOpenMPRuntime().emitInlinedDirective(
2798 *this, OMPD_taskloop_simd,
2799 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2800}
2801