blob: 211155edd235b9c549cc437ea2249d8f71d9ddf0 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022using namespace clang;
23using namespace CodeGen;
24
Alexey Bataev3392d762016-02-16 11:18:12 +000025namespace {
26/// Lexical scope for OpenMP executable constructs, that handles correct codegen
27/// for captured expressions.
28class OMPLexicalScope {
29 CodeGenFunction::LexicalScope Scope;
30 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
47
Alexey Bataev3392d762016-02-16 11:18:12 +000048public:
49 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
50 : Scope(CGF, S.getSourceRange()) {
51 emitPreInitStmt(CGF, S);
Alexey Bataev3392d762016-02-16 11:18:12 +000052 }
53};
54} // namespace
55
Alexey Bataev1189bd02016-01-26 12:20:39 +000056llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
57 auto &C = getContext();
58 llvm::Value *Size = nullptr;
59 auto SizeInChars = C.getTypeSizeInChars(Ty);
60 if (SizeInChars.isZero()) {
61 // getTypeSizeInChars() returns 0 for a VLA.
62 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
63 llvm::Value *ArraySize;
64 std::tie(ArraySize, Ty) = getVLASize(VAT);
65 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
66 }
67 SizeInChars = C.getTypeSizeInChars(Ty);
68 if (SizeInChars.isZero())
69 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
70 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
71 } else
72 Size = CGM.getSize(SizeInChars);
73 return Size;
74}
75
Alexey Bataev2377fe92015-09-10 08:12:02 +000076void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +000077 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000078 const RecordDecl *RD = S.getCapturedRecordDecl();
79 auto CurField = RD->field_begin();
80 auto CurCap = S.captures().begin();
81 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
82 E = S.capture_init_end();
83 I != E; ++I, ++CurField, ++CurCap) {
84 if (CurField->hasCapturedVLAType()) {
85 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000086 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +000087 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000088 } else if (CurCap->capturesThis())
89 CapturedVars.push_back(CXXThisValue);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000090 else if (CurCap->capturesVariableByCopy())
91 CapturedVars.push_back(
92 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
93 else {
94 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +000095 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +000096 }
Alexey Bataev2377fe92015-09-10 08:12:02 +000097 }
98}
99
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000100static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
101 StringRef Name, LValue AddrLV,
102 bool isReferenceType = false) {
103 ASTContext &Ctx = CGF.getContext();
104
105 auto *CastedPtr = CGF.EmitScalarConversion(
106 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
107 Ctx.getPointerType(DstType), SourceLocation());
108 auto TmpAddr =
109 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
110 .getAddress();
111
112 // If we are dealing with references we need to return the address of the
113 // reference instead of the reference of the value.
114 if (isReferenceType) {
115 QualType RefType = Ctx.getLValueReferenceType(DstType);
116 auto *RefVal = TmpAddr.getPointer();
117 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
118 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
119 CGF.EmitScalarInit(RefVal, TmpLVal);
120 }
121
122 return TmpAddr;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125llvm::Function *
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 assert(
128 CapturedStmtInfo &&
129 "CapturedStmtInfo should be set when generating the captured function");
130 const CapturedDecl *CD = S.getCapturedDecl();
131 const RecordDecl *RD = S.getCapturedRecordDecl();
132 assert(CD->hasBody() && "missing CapturedDecl body");
133
134 // Build the argument list.
135 ASTContext &Ctx = CGM.getContext();
136 FunctionArgList Args;
137 Args.append(CD->param_begin(),
138 std::next(CD->param_begin(), CD->getContextParamPosition()));
139 auto I = S.captures().begin();
140 for (auto *FD : RD->fields()) {
141 QualType ArgType = FD->getType();
142 IdentifierInfo *II = nullptr;
143 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000144
145 // If this is a capture by copy and the type is not a pointer, the outlined
146 // function argument type should be uintptr and the value properly casted to
147 // uintptr. This is necessary given that the runtime library is only able to
148 // deal with pointers. We can pass in the same way the VLA type sizes to the
149 // outlined function.
150 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
151 I->capturesVariableArrayType())
152 ArgType = Ctx.getUIntPtrType();
153
154 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000155 CapVar = I->getCapturedVar();
156 II = CapVar->getIdentifier();
157 } else if (I->capturesThis())
158 II = &getContext().Idents.get("this");
159 else {
160 assert(I->capturesVariableArrayType());
161 II = &getContext().Idents.get("vla");
162 }
163 if (ArgType->isVariablyModifiedType())
164 ArgType = getContext().getVariableArrayDecayedType(ArgType);
165 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
166 FD->getLocation(), II, ArgType));
167 ++I;
168 }
169 Args.append(
170 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
171 CD->param_end());
172
173 // Create the function declaration.
174 FunctionType::ExtInfo ExtInfo;
175 const CGFunctionInfo &FuncInfo =
176 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
177 /*IsVariadic=*/false);
178 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
179
180 llvm::Function *F = llvm::Function::Create(
181 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
182 CapturedStmtInfo->getHelperName(), &CGM.getModule());
183 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
184 if (CD->isNothrow())
185 F->addFnAttr(llvm::Attribute::NoUnwind);
186
187 // Generate the function.
188 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
189 CD->getBody()->getLocStart());
190 unsigned Cnt = CD->getContextParamPosition();
191 I = S.captures().begin();
192 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000193 // If we are capturing a pointer by copy we don't need to do anything, just
194 // use the value that we get from the arguments.
195 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
196 setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
Richard Trieucc3949d2016-02-18 22:34:54 +0000197 ++Cnt;
198 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000199 continue;
200 }
201
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 LValue ArgLVal =
203 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
204 AlignmentSource::Decl);
205 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206 LValue CastedArgLVal =
207 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
208 Args[Cnt]->getName(), ArgLVal),
209 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000210 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000211 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000212 auto VAT = FD->getCapturedVLAType();
213 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
214 } else if (I->capturesVariable()) {
215 auto *Var = I->getCapturedVar();
216 QualType VarTy = Var->getType();
217 Address ArgAddr = ArgLVal.getAddress();
218 if (!VarTy->isReferenceType()) {
219 ArgAddr = EmitLoadOfReference(
220 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
221 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000222 setAddrOfLocalVar(
223 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224 } else if (I->capturesVariableByCopy()) {
225 assert(!FD->getType()->isAnyPointerType() &&
226 "Not expecting a captured pointer.");
227 auto *Var = I->getCapturedVar();
228 QualType VarTy = Var->getType();
229 setAddrOfLocalVar(I->getCapturedVar(),
230 castValueFromUintptr(*this, FD->getType(),
231 Args[Cnt]->getName(), ArgLVal,
232 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 } else {
234 // If 'this' is captured, load it into CXXThisValue.
235 assert(I->capturesThis());
236 CXXThisValue =
237 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
238 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000239 ++Cnt;
240 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000241 }
242
Serge Pavlov3a561452015-12-06 14:32:39 +0000243 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 CapturedStmtInfo->EmitBody(*this, CD->getBody());
245 FinishFunction(CD->getBodyRBrace());
246
247 return F;
248}
249
Alexey Bataev9959db52014-05-06 10:08:46 +0000250//===----------------------------------------------------------------------===//
251// OpenMP Directive Emission
252//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000253void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000254 Address DestAddr, Address SrcAddr, QualType OriginalType,
255 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000256 // Perform element-by-element initialization.
257 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000258
259 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000260 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000261 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
262 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
263
264 auto SrcBegin = SrcAddr.getPointer();
265 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000266 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000267 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
268 // The basic structure here is a while-do loop.
269 auto BodyBB = createBasicBlock("omp.arraycpy.body");
270 auto DoneBB = createBasicBlock("omp.arraycpy.done");
271 auto IsEmpty =
272 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
273 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000274
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 // Enter the loop body, making that address the current address.
276 auto EntryBB = Builder.GetInsertBlock();
277 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000278
279 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
280
281 llvm::PHINode *SrcElementPHI =
282 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
283 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
284 Address SrcElementCurrent =
285 Address(SrcElementPHI,
286 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
287
288 llvm::PHINode *DestElementPHI =
289 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
290 DestElementPHI->addIncoming(DestBegin, EntryBB);
291 Address DestElementCurrent =
292 Address(DestElementPHI,
293 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000294
Alexey Bataev420d45b2015-04-14 05:11:24 +0000295 // Emit copy.
296 CopyGen(DestElementCurrent, SrcElementCurrent);
297
298 // Shift the address forward by one element.
299 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000300 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000301 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000302 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000303 // Check whether we've reached the end.
304 auto Done =
305 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
306 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000307 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
308 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000309
310 // Done.
311 EmitBlock(DoneBB, /*IsFinished=*/true);
312}
313
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000314/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000315/// \param DestAddr Address of the array.
316/// \param Type Type of array.
317/// \param Init Initial expression of array.
318static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
319 QualType Type, const Expr *Init) {
320 // Perform element-by-element initialization.
321 QualType ElementTy;
322
323 // Drill down to the base element type on both arrays.
324 auto ArrayTy = Type->getAsArrayTypeUnsafe();
325 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
326 DestAddr =
327 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
328
329 auto DestBegin = DestAddr.getPointer();
330 // Cast from pointer to array type to pointer to single element.
331 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
332 // The basic structure here is a while-do loop.
333 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
334 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
335 auto IsEmpty =
336 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
337 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
338
339 // Enter the loop body, making that address the current address.
340 auto EntryBB = CGF.Builder.GetInsertBlock();
341 CGF.EmitBlock(BodyBB);
342
343 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
344
345 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
346 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
347 DestElementPHI->addIncoming(DestBegin, EntryBB);
348 Address DestElementCurrent =
349 Address(DestElementPHI,
350 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
351
352 // Emit copy.
353 {
354 CodeGenFunction::RunCleanupsScope InitScope(CGF);
355 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
356 /*IsInitializer=*/false);
357 }
358
359 // Shift the address forward by one element.
360 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
361 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
362 // Check whether we've reached the end.
363 auto Done =
364 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
365 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
366 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
367
368 // Done.
369 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
370}
371
John McCall7f416cc2015-09-08 08:05:57 +0000372void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
373 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000374 const VarDecl *SrcVD, const Expr *Copy) {
375 if (OriginalType->isArrayType()) {
376 auto *BO = dyn_cast<BinaryOperator>(Copy);
377 if (BO && BO->getOpcode() == BO_Assign) {
378 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000379 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000380 } else {
381 // For arrays with complex element types perform element by element
382 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000383 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000384 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000385 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000386 // Working with the single array element, so have to remap
387 // destination and source variables to corresponding array
388 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000389 CodeGenFunction::OMPPrivateScope Remap(*this);
390 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000391 return DestElement;
392 });
393 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000394 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000395 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000396 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000397 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000398 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000399 } else {
400 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000401 CodeGenFunction::OMPPrivateScope Remap(*this);
402 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
403 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000404 (void)Remap.Privatize();
405 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000406 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000407 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000408}
409
Alexey Bataev69c62a92015-04-15 04:52:20 +0000410bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
411 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000412 if (!HaveInsertPoint())
413 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000414 bool FirstprivateIsLastprivate = false;
415 llvm::DenseSet<const VarDecl *> Lastprivates;
416 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
417 for (const auto *D : C->varlists())
418 Lastprivates.insert(
419 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
420 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000421 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000422 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000423 auto IRef = C->varlist_begin();
424 auto InitsRef = C->inits().begin();
425 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000426 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000427 FirstprivateIsLastprivate =
428 FirstprivateIsLastprivate ||
429 (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
430 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000431 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
432 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
433 bool IsRegistered;
434 DeclRefExpr DRE(
435 const_cast<VarDecl *>(OrigVD),
436 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
437 OrigVD) != nullptr,
438 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000439 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000440 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000441 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000442 // Emit VarDecl with copy init for arrays.
443 // Get the address of the original variable captured in current
444 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000445 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000446 auto Emission = EmitAutoVarAlloca(*VD);
447 auto *Init = VD->getInit();
448 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
449 // Perform simple memcpy.
450 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000451 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000452 } else {
453 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000454 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000455 [this, VDInit, Init](Address DestElement,
456 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000457 // Clean up any temporaries needed by the initialization.
458 RunCleanupsScope InitScope(*this);
459 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000460 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000461 EmitAnyExprToMem(Init, DestElement,
462 Init->getType().getQualifiers(),
463 /*IsInitializer*/ false);
464 LocalDeclMap.erase(VDInit);
465 });
466 }
467 EmitAutoVarCleanups(Emission);
468 return Emission.getAllocatedAddress();
469 });
470 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000471 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000472 // Emit private VarDecl with copy init.
473 // Remap temp VDInit variable to the address of the original
474 // variable
475 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000476 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 EmitDecl(*VD);
478 LocalDeclMap.erase(VDInit);
479 return GetAddrOfLocalVar(VD);
480 });
481 }
482 assert(IsRegistered &&
483 "firstprivate var already registered as private");
484 // Silence the warning about unused variable.
485 (void)IsRegistered;
486 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000487 ++IRef;
488 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000489 }
490 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000491 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000492}
493
Alexey Bataev03b340a2014-10-21 03:16:40 +0000494void CodeGenFunction::EmitOMPPrivateClause(
495 const OMPExecutableDirective &D,
496 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000497 if (!HaveInsertPoint())
498 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000499 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000500 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000501 auto IRef = C->varlist_begin();
502 for (auto IInit : C->private_copies()) {
503 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000504 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
505 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
506 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000507 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000508 // Emit private VarDecl with copy init.
509 EmitDecl(*VD);
510 return GetAddrOfLocalVar(VD);
511 });
512 assert(IsRegistered && "private var already registered as private");
513 // Silence the warning about unused variable.
514 (void)IsRegistered;
515 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000516 ++IRef;
517 }
518 }
519}
520
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000521bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000522 if (!HaveInsertPoint())
523 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000524 // threadprivate_var1 = master_threadprivate_var1;
525 // operator=(threadprivate_var2, master_threadprivate_var2);
526 // ...
527 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000528 llvm::DenseSet<const VarDecl *> CopiedVars;
529 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000530 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000531 auto IRef = C->varlist_begin();
532 auto ISrcRef = C->source_exprs().begin();
533 auto IDestRef = C->destination_exprs().begin();
534 for (auto *AssignOp : C->assignment_ops()) {
535 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000536 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000537 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000538 // Get the address of the master variable. If we are emitting code with
539 // TLS support, the address is passed from the master as field in the
540 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000541 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000542 if (getLangOpts().OpenMPUseTLS &&
543 getContext().getTargetInfo().isTLSSupported()) {
544 assert(CapturedStmtInfo->lookup(VD) &&
545 "Copyin threadprivates should have been captured!");
546 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
547 VK_LValue, (*IRef)->getExprLoc());
548 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000549 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000550 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000551 MasterAddr =
552 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
553 : CGM.GetAddrOfGlobal(VD),
554 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000555 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000556 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000557 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000558 if (CopiedVars.size() == 1) {
559 // At first check if current thread is a master thread. If it is, no
560 // need to copy data.
561 CopyBegin = createBasicBlock("copyin.not.master");
562 CopyEnd = createBasicBlock("copyin.not.master.end");
563 Builder.CreateCondBr(
564 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000565 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
566 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000567 CopyBegin, CopyEnd);
568 EmitBlock(CopyBegin);
569 }
570 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
571 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000572 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000573 }
574 ++IRef;
575 ++ISrcRef;
576 ++IDestRef;
577 }
578 }
579 if (CopyEnd) {
580 // Exit out of copying procedure for non-master thread.
581 EmitBlock(CopyEnd, /*IsFinished=*/true);
582 return true;
583 }
584 return false;
585}
586
Alexey Bataev38e89532015-04-16 04:54:05 +0000587bool CodeGenFunction::EmitOMPLastprivateClauseInit(
588 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000589 if (!HaveInsertPoint())
590 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000591 bool HasAtLeastOneLastprivate = false;
592 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000593 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000594 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000595 auto IRef = C->varlist_begin();
596 auto IDestRef = C->destination_exprs().begin();
597 for (auto *IInit : C->private_copies()) {
598 // Keep the address of the original variable for future update at the end
599 // of the loop.
600 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
601 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
602 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000603 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000604 DeclRefExpr DRE(
605 const_cast<VarDecl *>(OrigVD),
606 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
607 OrigVD) != nullptr,
608 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
609 return EmitLValue(&DRE).getAddress();
610 });
611 // Check if the variable is also a firstprivate: in this case IInit is
612 // not generated. Initialization of this variable will happen in codegen
613 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000614 if (IInit) {
615 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
616 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000617 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000618 // Emit private VarDecl with copy init.
619 EmitDecl(*VD);
620 return GetAddrOfLocalVar(VD);
621 });
622 assert(IsRegistered &&
623 "lastprivate var already registered as private");
624 (void)IsRegistered;
625 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000626 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000627 ++IRef;
628 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000629 }
630 }
631 return HasAtLeastOneLastprivate;
632}
633
634void CodeGenFunction::EmitOMPLastprivateClauseFinal(
635 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000636 if (!HaveInsertPoint())
637 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000638 // Emit following code:
639 // if (<IsLastIterCond>) {
640 // orig_var1 = private_orig_var1;
641 // ...
642 // orig_varn = private_orig_varn;
643 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000644 llvm::BasicBlock *ThenBB = nullptr;
645 llvm::BasicBlock *DoneBB = nullptr;
646 if (IsLastIterCond) {
647 ThenBB = createBasicBlock(".omp.lastprivate.then");
648 DoneBB = createBasicBlock(".omp.lastprivate.done");
649 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
650 EmitBlock(ThenBB);
651 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000652 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000653 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000654 auto IC = LoopDirective->counters().begin();
655 for (auto F : LoopDirective->finals()) {
656 auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
657 LoopCountersAndUpdates[D] = F;
658 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000659 }
660 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000661 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
662 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
663 auto IRef = C->varlist_begin();
664 auto ISrcRef = C->source_exprs().begin();
665 auto IDestRef = C->destination_exprs().begin();
666 for (auto *AssignOp : C->assignment_ops()) {
667 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
668 QualType Type = PrivateVD->getType();
669 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
670 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
671 // If lastprivate variable is a loop control variable for loop-based
672 // directive, update its value before copyin back to original
673 // variable.
674 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
675 EmitIgnoredExpr(UpExpr);
676 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
677 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
678 // Get the address of the original variable.
679 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
680 // Get the address of the private variable.
681 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
682 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
683 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000684 Address(Builder.CreateLoad(PrivateAddr),
685 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000686 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000687 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000688 ++IRef;
689 ++ISrcRef;
690 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000691 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000692 if (auto *PostUpdate = C->getPostUpdateExpr())
693 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000694 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000695 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000696 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000697}
698
Alexey Bataev31300ed2016-02-04 11:27:03 +0000699static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
700 LValue BaseLV, llvm::Value *Addr) {
701 Address Tmp = Address::invalid();
702 Address TopTmp = Address::invalid();
703 Address MostTopTmp = Address::invalid();
704 BaseTy = BaseTy.getNonReferenceType();
705 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
706 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
707 Tmp = CGF.CreateMemTemp(BaseTy);
708 if (TopTmp.isValid())
709 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
710 else
711 MostTopTmp = Tmp;
712 TopTmp = Tmp;
713 BaseTy = BaseTy->getPointeeType();
714 }
715 llvm::Type *Ty = BaseLV.getPointer()->getType();
716 if (Tmp.isValid())
717 Ty = Tmp.getElementType();
718 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
719 if (Tmp.isValid()) {
720 CGF.Builder.CreateStore(Addr, Tmp);
721 return MostTopTmp;
722 }
723 return Address(Addr, BaseLV.getAlignment());
724}
725
726static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
727 LValue BaseLV) {
728 BaseTy = BaseTy.getNonReferenceType();
729 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
730 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
731 if (auto *PtrTy = BaseTy->getAs<PointerType>())
732 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
733 else {
734 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
735 BaseTy->castAs<ReferenceType>());
736 }
737 BaseTy = BaseTy->getPointeeType();
738 }
739 return CGF.MakeAddrLValue(
740 Address(
741 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
742 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
743 BaseLV.getAlignment()),
744 BaseLV.getType(), BaseLV.getAlignmentSource());
745}
746
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000747void CodeGenFunction::EmitOMPReductionClauseInit(
748 const OMPExecutableDirective &D,
749 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000750 if (!HaveInsertPoint())
751 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000752 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000753 auto ILHS = C->lhs_exprs().begin();
754 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000755 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000756 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000757 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000758 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
759 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
760 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
761 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
762 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
763 Base = TempOASE->getBase()->IgnoreParenImpCasts();
764 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
765 Base = TempASE->getBase()->IgnoreParenImpCasts();
766 auto *DE = cast<DeclRefExpr>(Base);
767 auto *OrigVD = cast<VarDecl>(DE->getDecl());
768 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
769 auto OASELValueUB =
770 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
771 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000772 LValue BaseLValue =
773 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
774 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000775 // Store the address of the original variable associated with the LHS
776 // implicit variable.
777 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
778 return OASELValueLB.getAddress();
779 });
780 // Emit reduction copy.
781 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000782 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
783 OASELValueUB, OriginalBaseLValue]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000784 // Emit VarDecl with copy init for arrays.
785 // Get the address of the original variable captured in current
786 // captured region.
787 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
788 OASELValueLB.getPointer());
789 Size = Builder.CreateNUWAdd(
790 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
791 CodeGenFunction::OpaqueValueMapping OpaqueMap(
792 *this, cast<OpaqueValueExpr>(
793 getContext()
794 .getAsVariableArrayType(PrivateVD->getType())
795 ->getSizeExpr()),
796 RValue::get(Size));
797 EmitVariablyModifiedType(PrivateVD->getType());
798 auto Emission = EmitAutoVarAlloca(*PrivateVD);
799 auto Addr = Emission.getAllocatedAddress();
800 auto *Init = PrivateVD->getInit();
801 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
802 EmitAutoVarCleanups(Emission);
803 // Emit private VarDecl with reduction init.
804 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
805 OASELValueLB.getPointer());
806 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000807 return castToBase(*this, OrigVD->getType(),
808 OASELValueLB.getType(), OriginalBaseLValue,
809 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000810 });
811 assert(IsRegistered && "private var already registered as private");
812 // Silence the warning about unused variable.
813 (void)IsRegistered;
814 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
815 return GetAddrOfLocalVar(PrivateVD);
816 });
817 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
818 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
819 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
820 Base = TempASE->getBase()->IgnoreParenImpCasts();
821 auto *DE = cast<DeclRefExpr>(Base);
822 auto *OrigVD = cast<VarDecl>(DE->getDecl());
823 auto ASELValue = EmitLValue(ASE);
824 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000825 LValue BaseLValue = loadToBegin(
826 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000827 // Store the address of the original variable associated with the LHS
828 // implicit variable.
829 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
830 return ASELValue.getAddress();
831 });
832 // Emit reduction copy.
833 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000834 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000835 OriginalBaseLValue]() -> Address {
836 // Emit private VarDecl with reduction init.
837 EmitDecl(*PrivateVD);
838 auto Addr = GetAddrOfLocalVar(PrivateVD);
839 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
840 ASELValue.getPointer());
841 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000842 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
843 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000844 });
845 assert(IsRegistered && "private var already registered as private");
846 // Silence the warning about unused variable.
847 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000848 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
849 return Builder.CreateElementBitCast(
850 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
851 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000852 });
853 } else {
854 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000855 QualType Type = PrivateVD->getType();
856 if (getContext().getAsArrayType(Type)) {
857 // Store the address of the original variable associated with the LHS
858 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000859 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
860 CapturedStmtInfo->lookup(OrigVD) != nullptr,
861 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +0000862 Address OriginalAddr = EmitLValue(&DRE).getAddress();
863 PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
864 LHSVD]() -> Address {
865 return Builder.CreateElementBitCast(
866 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
867 "lhs.begin");
868 });
869 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
870 if (Type->isVariablyModifiedType()) {
871 CodeGenFunction::OpaqueValueMapping OpaqueMap(
872 *this, cast<OpaqueValueExpr>(
873 getContext()
874 .getAsVariableArrayType(PrivateVD->getType())
875 ->getSizeExpr()),
876 RValue::get(
877 getTypeSize(OrigVD->getType().getNonReferenceType())));
878 EmitVariablyModifiedType(Type);
879 }
880 auto Emission = EmitAutoVarAlloca(*PrivateVD);
881 auto Addr = Emission.getAllocatedAddress();
882 auto *Init = PrivateVD->getInit();
883 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
884 EmitAutoVarCleanups(Emission);
885 return Emission.getAllocatedAddress();
886 });
887 assert(IsRegistered && "private var already registered as private");
888 // Silence the warning about unused variable.
889 (void)IsRegistered;
890 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
891 return Builder.CreateElementBitCast(
892 GetAddrOfLocalVar(PrivateVD),
893 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
894 });
895 } else {
896 // Store the address of the original variable associated with the LHS
897 // implicit variable.
898 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
899 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
900 CapturedStmtInfo->lookup(OrigVD) != nullptr,
901 IRef->getType(), VK_LValue, IRef->getExprLoc());
902 return EmitLValue(&DRE).getAddress();
903 });
904 // Emit reduction copy.
905 bool IsRegistered =
906 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
907 // Emit private VarDecl with reduction init.
908 EmitDecl(*PrivateVD);
909 return GetAddrOfLocalVar(PrivateVD);
910 });
911 assert(IsRegistered && "private var already registered as private");
912 // Silence the warning about unused variable.
913 (void)IsRegistered;
914 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
915 return GetAddrOfLocalVar(PrivateVD);
916 });
917 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000918 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000919 ++ILHS;
920 ++IRHS;
921 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000922 }
923 }
924}
925
926void CodeGenFunction::EmitOMPReductionClauseFinal(
927 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000928 if (!HaveInsertPoint())
929 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000930 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000931 llvm::SmallVector<const Expr *, 8> LHSExprs;
932 llvm::SmallVector<const Expr *, 8> RHSExprs;
933 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000934 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000935 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000936 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000937 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000938 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
939 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
940 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
941 }
942 if (HasAtLeastOneReduction) {
943 // Emit nowait reduction if nowait clause is present or directive is a
944 // parallel directive (it always has implicit barrier).
945 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000946 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000947 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000948 isOpenMPParallelDirective(D.getDirectiveKind()) ||
949 D.getDirectiveKind() == OMPD_simd,
950 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000951 }
952}
953
Alexey Bataev61205072016-03-02 04:57:40 +0000954static void emitPostUpdateForReductionClause(
955 CodeGenFunction &CGF, const OMPExecutableDirective &D,
956 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
957 if (!CGF.HaveInsertPoint())
958 return;
959 llvm::BasicBlock *DoneBB = nullptr;
960 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
961 if (auto *PostUpdate = C->getPostUpdateExpr()) {
962 if (!DoneBB) {
963 if (auto *Cond = CondGen(CGF)) {
964 // If the first post-update expression is found, emit conditional
965 // block if it was requested.
966 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
967 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
968 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
969 CGF.EmitBlock(ThenBB);
970 }
971 }
972 CGF.EmitIgnoredExpr(PostUpdate);
973 }
974 }
975 if (DoneBB)
976 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
977}
978
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000979static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
980 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000981 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000982 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000983 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000984 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
985 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000986 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
987 emitParallelOrTeamsOutlinedFunction(S,
988 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000989 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000990 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000991 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
992 /*IgnoreResultAssign*/ true);
993 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
994 CGF, NumThreads, NumThreadsClause->getLocStart());
995 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000996 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000997 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000998 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
999 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1000 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001001 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001002 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1003 if (C->getNameModifier() == OMPD_unknown ||
1004 C->getNameModifier() == OMPD_parallel) {
1005 IfCond = C->getCondition();
1006 break;
1007 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001008 }
1009 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001010 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001011}
1012
1013void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001014 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001015 // Emit parallel region as a standalone region.
1016 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1017 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001018 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001019 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1020 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001021 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001022 // propagation master's thread values of threadprivate variables to local
1023 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001024 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1025 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1026 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001027 }
1028 CGF.EmitOMPPrivateClause(S, PrivateScope);
1029 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1030 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001031 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001032 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001033 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001034 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001035 emitPostUpdateForReductionClause(
1036 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001037}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001038
Alexey Bataev0f34da12015-07-02 04:17:07 +00001039void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1040 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001041 RunCleanupsScope BodyScope(*this);
1042 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001043 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001044 EmitIgnoredExpr(I);
1045 }
Alexander Musman3276a272015-03-21 10:12:56 +00001046 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001047 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +00001048 for (auto U : C->updates()) {
1049 EmitIgnoredExpr(U);
1050 }
1051 }
1052
Alexander Musmana5f070a2014-10-01 06:03:56 +00001053 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001054 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001055 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001056 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001057 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001058 // The end (updates/cleanups).
1059 EmitBlock(Continue.getBlock());
1060 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001061}
1062
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001063void CodeGenFunction::EmitOMPInnerLoop(
1064 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1065 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001066 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1067 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001068 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001069
1070 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001071 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001072 EmitBlock(CondBlock);
1073 LoopStack.push(CondBlock);
1074
1075 // If there are any cleanups between here and the loop-exit scope,
1076 // create a block to stage a loop exit along.
1077 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001078 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001079 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001080
Alexander Musmand196ef22014-10-07 08:57:09 +00001081 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001082
Alexey Bataev2df54a02015-03-12 08:53:29 +00001083 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001084 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001085 if (ExitBlock != LoopExit.getBlock()) {
1086 EmitBlock(ExitBlock);
1087 EmitBranchThroughCleanup(LoopExit);
1088 }
1089
1090 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001091 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001092
1093 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001094 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001095 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1096
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001097 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001098
1099 // Emit "IV = IV + 1" and a back-edge to the condition block.
1100 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001101 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001102 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001103 BreakContinueStack.pop_back();
1104 EmitBranch(CondBlock);
1105 LoopStack.pop();
1106 // Emit the fall-through block.
1107 EmitBlock(LoopExit.getBlock());
1108}
1109
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001110void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001111 if (!HaveInsertPoint())
1112 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001113 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001114 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001115 for (auto Init : C->inits()) {
1116 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001117 auto *OrigVD = cast<VarDecl>(
1118 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1119 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1120 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1121 VD->getInit()->getType(), VK_LValue,
1122 VD->getInit()->getExprLoc());
1123 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1124 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +00001125 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001126 /*capturedByInit=*/false);
1127 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001128 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001129 // Emit the linear steps for the linear clauses.
1130 // If a step is not constant, it is pre-calculated before the loop.
1131 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1132 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001133 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001134 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001135 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001136 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001137 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001138}
1139
1140static void emitLinearClauseFinal(CodeGenFunction &CGF,
1141 const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001142 if (!CGF.HaveInsertPoint())
1143 return;
Alexander Musman3276a272015-03-21 10:12:56 +00001144 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001145 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001146 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +00001147 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001148 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1149 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001150 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001151 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001152 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001153 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001154 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001155 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001156 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001157 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001158 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001159 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001160 if (auto *PostUpdate = C->getPostUpdateExpr())
1161 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001162 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001163}
1164
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001165static void emitAlignedClause(CodeGenFunction &CGF,
1166 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001167 if (!CGF.HaveInsertPoint())
1168 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001169 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001170 unsigned ClauseAlignment = 0;
1171 if (auto AlignmentExpr = Clause->getAlignment()) {
1172 auto AlignmentCI =
1173 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1174 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001175 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001176 for (auto E : Clause->varlists()) {
1177 unsigned Alignment = ClauseAlignment;
1178 if (Alignment == 0) {
1179 // OpenMP [2.8.1, Description]
1180 // If no optional parameter is specified, implementation-defined default
1181 // alignments for SIMD instructions on the target platforms are assumed.
1182 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001183 CGF.getContext()
1184 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1185 E->getType()->getPointeeType()))
1186 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001187 }
1188 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1189 "alignment is not power of 2");
1190 if (Alignment != 0) {
1191 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1192 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1193 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001194 }
1195 }
1196}
1197
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001198static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001199 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001200 ArrayRef<Expr *> Counters,
1201 ArrayRef<Expr *> PrivateCounters) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001202 if (!CGF.HaveInsertPoint())
1203 return;
Alexey Bataeva8899172015-08-06 12:30:57 +00001204 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001205 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001206 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1207 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001208 Address Addr = Address::invalid();
1209 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001210 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001211 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001212 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001213 Addr = VarEmission.getAllocatedAddress();
1214 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001215 });
John McCall7f416cc2015-09-08 08:05:57 +00001216 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001217 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001218 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001219}
1220
Alexey Bataev62dbb972015-04-22 11:59:37 +00001221static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1222 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1223 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001224 if (!CGF.HaveInsertPoint())
1225 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001226 {
1227 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001228 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1229 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001230 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001231 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001232 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001233 CGF.EmitIgnoredExpr(I);
1234 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001235 }
1236 // Check that loop is executed at least one time.
1237 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1238}
1239
Alexander Musman3276a272015-03-21 10:12:56 +00001240static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001241emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001242 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001243 if (!CGF.HaveInsertPoint())
1244 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001245 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001246 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001247 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001248 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1249 auto *PrivateVD =
1250 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001251 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001252 // Emit private VarDecl with copy init.
1253 CGF.EmitVarDecl(*PrivateVD);
1254 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001255 });
1256 assert(IsRegistered && "linear var already registered as private");
1257 // Silence the warning about unused variable.
1258 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001259 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001260 }
1261 }
1262}
1263
Alexey Bataev45bfad52015-08-21 12:19:04 +00001264static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001265 const OMPExecutableDirective &D,
1266 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001267 if (!CGF.HaveInsertPoint())
1268 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001269 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001270 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1271 /*ignoreResult=*/true);
1272 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1273 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1274 // In presence of finite 'safelen', it may be unsafe to mark all
1275 // the memory instructions parallel, because loop-carried
1276 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001277 if (!IsMonotonic)
1278 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001279 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001280 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1281 /*ignoreResult=*/true);
1282 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001283 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001284 // In presence of finite 'safelen', it may be unsafe to mark all
1285 // the memory instructions parallel, because loop-carried
1286 // dependences of 'safelen' iterations are possible.
1287 CGF.LoopStack.setParallel(false);
1288 }
1289}
1290
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001291void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1292 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001293 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001294 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001295 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001296 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001297}
1298
1299void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001300 if (!HaveInsertPoint())
1301 return;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001302 auto IC = D.counters().begin();
1303 for (auto F : D.finals()) {
1304 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001305 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001306 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1307 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1308 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001309 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001310 OMPPrivateScope VarScope(*this);
1311 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001312 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001313 (void)VarScope.Privatize();
1314 EmitIgnoredExpr(F);
1315 }
1316 ++IC;
1317 }
1318 emitLinearClauseFinal(*this, D);
1319}
1320
Alexander Musman515ad8c2014-05-22 08:54:05 +00001321void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001322 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001323 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001324 // for (IV in 0..LastIteration) BODY;
1325 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001326 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001327 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001328
Alexey Bataev62dbb972015-04-22 11:59:37 +00001329 // Emit: if (PreCond) - begin.
1330 // If the condition constant folds and can be elided, avoid emitting the
1331 // whole loop.
1332 bool CondConstant;
1333 llvm::BasicBlock *ContBlock = nullptr;
1334 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1335 if (!CondConstant)
1336 return;
1337 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001338 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1339 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001340 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1341 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001342 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001343 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001344 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001345
1346 // Emit the loop iteration variable.
1347 const Expr *IVExpr = S.getIterationVariable();
1348 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1349 CGF.EmitVarDecl(*IVDecl);
1350 CGF.EmitIgnoredExpr(S.getInit());
1351
1352 // Emit the iterations count variable.
1353 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001354 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001355 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1356 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1357 // Emit calculation of the iterations count.
1358 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001359 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001360
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001361 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001362
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001363 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001364 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001365 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001366 {
1367 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001368 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1369 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001370 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001371 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001372 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001373 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001374 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001375 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1376 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001377 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001378 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001379 CGF.EmitStopPoint(&S);
1380 },
1381 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001382 // Emit final copy of the lastprivate variables at the end of loops.
1383 if (HasLastprivateClause) {
1384 CGF.EmitOMPLastprivateClauseFinal(S);
1385 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001386 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001387 emitPostUpdateForReductionClause(
1388 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001389 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001390 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001391 // Emit: if (PreCond) - end.
1392 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001393 CGF.EmitBranch(ContBlock);
1394 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001395 }
1396 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001397 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001398}
1399
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001400void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001401 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1402 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001403 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001404
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001405 const Expr *IVExpr = S.getIterationVariable();
1406 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1407 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1408
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001409 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1410
1411 // Start the loop with a block that tests the condition.
1412 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1413 EmitBlock(CondBlock);
1414 LoopStack.push(CondBlock);
1415
1416 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001417 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001418 // UB = min(UB, GlobalUB)
1419 EmitIgnoredExpr(S.getEnsureUpperBound());
1420 // IV = LB
1421 EmitIgnoredExpr(S.getInit());
1422 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001423 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001424 } else {
1425 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1426 IL, LB, UB, ST);
1427 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001428
1429 // If there are any cleanups between here and the loop-exit scope,
1430 // create a block to stage a loop exit along.
1431 auto ExitBlock = LoopExit.getBlock();
1432 if (LoopScope.requiresCleanups())
1433 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1434
1435 auto LoopBody = createBasicBlock("omp.dispatch.body");
1436 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1437 if (ExitBlock != LoopExit.getBlock()) {
1438 EmitBlock(ExitBlock);
1439 EmitBranchThroughCleanup(LoopExit);
1440 }
1441 EmitBlock(LoopBody);
1442
Alexander Musman92bdaab2015-03-12 13:37:50 +00001443 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1444 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001445 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001446 EmitIgnoredExpr(S.getInit());
1447
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001448 // Create a block for the increment.
1449 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1450 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1451
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001452 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1453 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001454 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1455 LoopStack.setParallel(!IsMonotonic);
1456 else
1457 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001458
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001459 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001460 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1461 [&S, LoopExit](CodeGenFunction &CGF) {
1462 CGF.EmitOMPLoopBody(S, LoopExit);
1463 CGF.EmitStopPoint(&S);
1464 },
1465 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1466 if (Ordered) {
1467 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1468 CGF, Loc, IVSize, IVSigned);
1469 }
1470 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001471
1472 EmitBlock(Continue.getBlock());
1473 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001474 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001475 // Emit "LB = LB + Stride", "UB = UB + Stride".
1476 EmitIgnoredExpr(S.getNextLowerBound());
1477 EmitIgnoredExpr(S.getNextUpperBound());
1478 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001479
1480 EmitBranch(CondBlock);
1481 LoopStack.pop();
1482 // Emit the fall-through block.
1483 EmitBlock(LoopExit.getBlock());
1484
1485 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001486 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001487 RT.emitForStaticFinish(*this, S.getLocEnd());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001488
1489}
1490
1491void CodeGenFunction::EmitOMPForOuterLoop(
1492 OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1493 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1494 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1495 auto &RT = CGM.getOpenMPRuntime();
1496
1497 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1498 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1499
1500 assert((Ordered ||
1501 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1502 "static non-chunked schedule does not need outer loop");
1503
1504 // Emit outer loop.
1505 //
1506 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1507 // When schedule(dynamic,chunk_size) is specified, the iterations are
1508 // distributed to threads in the team in chunks as the threads request them.
1509 // Each thread executes a chunk of iterations, then requests another chunk,
1510 // until no chunks remain to be distributed. Each chunk contains chunk_size
1511 // iterations, except for the last chunk to be distributed, which may have
1512 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1513 //
1514 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1515 // to threads in the team in chunks as the executing threads request them.
1516 // Each thread executes a chunk of iterations, then requests another chunk,
1517 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1518 // each chunk is proportional to the number of unassigned iterations divided
1519 // by the number of threads in the team, decreasing to 1. For a chunk_size
1520 // with value k (greater than 1), the size of each chunk is determined in the
1521 // same way, with the restriction that the chunks do not contain fewer than k
1522 // iterations (except for the last chunk to be assigned, which may have fewer
1523 // than k iterations).
1524 //
1525 // When schedule(auto) is specified, the decision regarding scheduling is
1526 // delegated to the compiler and/or runtime system. The programmer gives the
1527 // implementation the freedom to choose any possible mapping of iterations to
1528 // threads in the team.
1529 //
1530 // When schedule(runtime) is specified, the decision regarding scheduling is
1531 // deferred until run time, and the schedule and chunk size are taken from the
1532 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1533 // implementation defined
1534 //
1535 // while(__kmpc_dispatch_next(&LB, &UB)) {
1536 // idx = LB;
1537 // while (idx <= UB) { BODY; ++idx;
1538 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1539 // } // inner loop
1540 // }
1541 //
1542 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1543 // When schedule(static, chunk_size) is specified, iterations are divided into
1544 // chunks of size chunk_size, and the chunks are assigned to the threads in
1545 // the team in a round-robin fashion in the order of the thread number.
1546 //
1547 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1548 // while (idx <= UB) { BODY; ++idx; } // inner loop
1549 // LB = LB + ST;
1550 // UB = UB + ST;
1551 // }
1552 //
1553
1554 const Expr *IVExpr = S.getIterationVariable();
1555 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1556 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1557
1558 if (DynamicOrOrdered) {
1559 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1560 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1561 IVSize, IVSigned, Ordered, UBVal, Chunk);
1562 } else {
1563 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1564 Ordered, IL, LB, UB, ST, Chunk);
1565 }
1566
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001567 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001568 ST, IL, Chunk);
1569}
1570
1571void CodeGenFunction::EmitOMPDistributeOuterLoop(
1572 OpenMPDistScheduleClauseKind ScheduleKind,
1573 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1574 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1575
1576 auto &RT = CGM.getOpenMPRuntime();
1577
1578 // Emit outer loop.
1579 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1580 // dynamic
1581 //
1582
1583 const Expr *IVExpr = S.getIterationVariable();
1584 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1585 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1586
1587 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1588 IVSize, IVSigned, /* Ordered = */ false,
1589 IL, LB, UB, ST, Chunk);
1590
1591 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1592 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001593}
1594
Alexander Musmanc6388682014-12-15 07:07:06 +00001595/// \brief Emit a helper variable and return corresponding lvalue.
1596static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1597 const DeclRefExpr *Helper) {
1598 auto VDecl = cast<VarDecl>(Helper->getDecl());
1599 CGF.EmitVarDecl(*VDecl);
1600 return CGF.EmitLValue(Helper);
1601}
1602
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001603namespace {
1604 struct ScheduleKindModifiersTy {
1605 OpenMPScheduleClauseKind Kind;
1606 OpenMPScheduleClauseModifier M1;
1607 OpenMPScheduleClauseModifier M2;
1608 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1609 OpenMPScheduleClauseModifier M1,
1610 OpenMPScheduleClauseModifier M2)
1611 : Kind(Kind), M1(M1), M2(M2) {}
1612 };
1613} // namespace
1614
Alexey Bataev38e89532015-04-16 04:54:05 +00001615bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001616 // Emit the loop iteration variable.
1617 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1618 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1619 EmitVarDecl(*IVDecl);
1620
1621 // Emit the iterations count variable.
1622 // If it is not a variable, Sema decided to calculate iterations count on each
1623 // iteration (e.g., it is foldable into a constant).
1624 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1625 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1626 // Emit calculation of the iterations count.
1627 EmitIgnoredExpr(S.getCalcLastIteration());
1628 }
1629
1630 auto &RT = CGM.getOpenMPRuntime();
1631
Alexey Bataev38e89532015-04-16 04:54:05 +00001632 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001633 // Check pre-condition.
1634 {
1635 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001636 // If the condition constant folds and can be elided, avoid emitting the
1637 // whole loop.
1638 bool CondConstant;
1639 llvm::BasicBlock *ContBlock = nullptr;
1640 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1641 if (!CondConstant)
1642 return false;
1643 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001644 auto *ThenBlock = createBasicBlock("omp.precond.then");
1645 ContBlock = createBasicBlock("omp.precond.end");
1646 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001647 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001648 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001649 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001650 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001651
1652 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001653 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001654 // Emit 'then' code.
1655 {
1656 // Emit helper vars inits.
1657 LValue LB =
1658 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1659 LValue UB =
1660 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1661 LValue ST =
1662 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1663 LValue IL =
1664 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1665
1666 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001667 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1668 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001669 // initialization of firstprivate variables and post-update of
1670 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001671 CGM.getOpenMPRuntime().emitBarrierCall(
1672 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1673 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001674 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001675 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001676 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001677 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001678 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1679 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001680 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001681 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001682
1683 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00001684 llvm::Value *Chunk = nullptr;
1685 OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1686 OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1687 OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1688 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1689 ScheduleKind = C->getScheduleKind();
1690 M1 = C->getFirstScheduleModifier();
1691 M2 = C->getSecondScheduleModifier();
1692 if (const auto *Ch = C->getChunkSize()) {
1693 Chunk = EmitScalarExpr(Ch);
1694 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1695 S.getIterationVariable()->getType(),
1696 S.getLocStart());
1697 }
1698 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001699 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1700 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001701 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001702 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1703 // If the static schedule kind is specified or if the ordered clause is
1704 // specified, and if no monotonic modifier is specified, the effect will
1705 // be as if the monotonic modifier was specified.
Alexander Musmanc6388682014-12-15 07:07:06 +00001706 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001707 /* Chunked */ Chunk != nullptr) &&
1708 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001709 if (isOpenMPSimdDirective(S.getDirectiveKind()))
1710 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00001711 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1712 // When no chunk_size is specified, the iteration space is divided into
1713 // chunks that are approximately equal in size, and at most one chunk is
1714 // distributed to each thread. Note that the size of the chunks is
1715 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001716 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1717 IVSize, IVSigned, Ordered,
1718 IL.getAddress(), LB.getAddress(),
1719 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001720 auto LoopExit =
1721 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001722 // UB = min(UB, GlobalUB);
1723 EmitIgnoredExpr(S.getEnsureUpperBound());
1724 // IV = LB;
1725 EmitIgnoredExpr(S.getInit());
1726 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001727 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1728 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001729 [&S, LoopExit](CodeGenFunction &CGF) {
1730 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001731 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001732 },
1733 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001734 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001735 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001736 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001737 } else {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001738 const bool IsMonotonic = Ordered ||
1739 ScheduleKind == OMPC_SCHEDULE_static ||
1740 ScheduleKind == OMPC_SCHEDULE_unknown ||
1741 M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1742 M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001743 // Emit the outer loop, which requests its work chunk [LB..UB] from
1744 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001745 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001746 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1747 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001748 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001749 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001750 // Emit post-update of the reduction variables if IsLastIter != 0.
1751 emitPostUpdateForReductionClause(
1752 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1753 return CGF.Builder.CreateIsNotNull(
1754 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1755 });
Alexey Bataev38e89532015-04-16 04:54:05 +00001756 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1757 if (HasLastprivateClause)
1758 EmitOMPLastprivateClauseFinal(
1759 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001760 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001761 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1762 EmitOMPSimdFinal(S);
1763 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001764 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001765 if (ContBlock) {
1766 EmitBranch(ContBlock);
1767 EmitBlock(ContBlock, true);
1768 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001769 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001770 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001771}
1772
1773void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001774 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001775 {
1776 OMPLexicalScope Scope(*this, S);
1777 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1778 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1779 };
1780 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1781 S.hasCancel());
1782 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001783
1784 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001785 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001786 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1787 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001788}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001789
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001790void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001791 bool HasLastprivates = false;
Alexey Bataev3392d762016-02-16 11:18:12 +00001792 {
1793 OMPLexicalScope Scope(*this, S);
1794 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1795 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1796 };
1797 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1798 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001799
1800 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001801 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001802 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1803 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001804}
1805
Alexey Bataev2df54a02015-03-12 08:53:29 +00001806static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1807 const Twine &Name,
1808 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001809 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001810 if (Init)
1811 CGF.EmitScalarInit(Init, LVal);
1812 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001813}
1814
Alexey Bataev3392d762016-02-16 11:18:12 +00001815void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001816 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1817 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001818 bool HasLastprivates = false;
1819 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1820 auto &C = CGF.CGM.getContext();
1821 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1822 // Emit helper vars inits.
1823 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1824 CGF.Builder.getInt32(0));
1825 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1826 : CGF.Builder.getInt32(0);
1827 LValue UB =
1828 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1829 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1830 CGF.Builder.getInt32(1));
1831 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1832 CGF.Builder.getInt32(0));
1833 // Loop counter.
1834 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1835 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1836 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1837 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1838 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1839 // Generate condition for loop.
1840 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1841 OK_Ordinary, S.getLocStart(),
1842 /*fpContractable=*/false);
1843 // Increment for loop counter.
1844 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1845 S.getLocStart());
1846 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1847 // Iterate through all sections and emit a switch construct:
1848 // switch (IV) {
1849 // case 0:
1850 // <SectionStmt[0]>;
1851 // break;
1852 // ...
1853 // case <NumSection> - 1:
1854 // <SectionStmt[<NumSection> - 1]>;
1855 // break;
1856 // }
1857 // .omp.sections.exit:
1858 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1859 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1860 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1861 CS == nullptr ? 1 : CS->size());
1862 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001863 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001864 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001865 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1866 CGF.EmitBlock(CaseBB);
1867 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001868 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001869 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001870 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001871 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001872 } else {
1873 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1874 CGF.EmitBlock(CaseBB);
1875 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1876 CGF.EmitStmt(Stmt);
1877 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001878 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001879 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001880 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001881
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001882 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1883 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001884 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001885 // initialization of firstprivate variables and post-update of lastprivate
1886 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001887 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1888 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1889 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001890 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001891 CGF.EmitOMPPrivateClause(S, LoopScope);
1892 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1893 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1894 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001895
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001896 // Emit static non-chunked loop.
1897 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1898 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1899 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1900 UB.getAddress(), ST.getAddress());
1901 // UB = min(UB, GlobalUB);
1902 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1903 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1904 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1905 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1906 // IV = LB;
1907 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1908 // while (idx <= UB) { BODY; ++idx; }
1909 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1910 [](CodeGenFunction &) {});
1911 // Tell the runtime we are done.
1912 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1913 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001914 // Emit post-update of the reduction variables if IsLastIter != 0.
1915 emitPostUpdateForReductionClause(
1916 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
1917 return CGF.Builder.CreateIsNotNull(
1918 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
1919 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001920
1921 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1922 if (HasLastprivates)
1923 CGF.EmitOMPLastprivateClauseFinal(
1924 S, CGF.Builder.CreateIsNotNull(
1925 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001926 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001927
1928 bool HasCancel = false;
1929 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1930 HasCancel = OSD->hasCancel();
1931 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1932 HasCancel = OPSD->hasCancel();
1933 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1934 HasCancel);
1935 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1936 // clause. Otherwise the barrier will be generated by the codegen for the
1937 // directive.
1938 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001939 // Emit implicit barrier to synchronize threads and avoid data races on
1940 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001941 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1942 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001943 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001944}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001945
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001946void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001947 {
1948 OMPLexicalScope Scope(*this, S);
1949 EmitSections(S);
1950 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001951 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001952 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001953 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1954 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00001955 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001956}
1957
1958void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001959 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001960 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1961 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001962 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001963 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1964 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001965}
1966
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001967void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001968 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001969 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001970 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001971 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001972 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001973 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001974 // Build a list of copyprivate variables along with helper expressions
1975 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001976 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001977 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001978 DestExprs.append(C->destination_exprs().begin(),
1979 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001980 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001981 AssignmentOps.append(C->assignment_ops().begin(),
1982 C->assignment_ops().end());
1983 }
Alexey Bataev3392d762016-02-16 11:18:12 +00001984 {
1985 OMPLexicalScope Scope(*this, S);
1986 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev417089f2016-02-17 13:19:37 +00001987 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +00001988 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
Alexey Bataev417089f2016-02-17 13:19:37 +00001989 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev3392d762016-02-16 11:18:12 +00001990 CGF.EmitOMPPrivateClause(S, SingleScope);
1991 (void)SingleScope.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +00001992 CGF.EmitStmt(
1993 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1994 };
1995 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1996 CopyprivateVars, DestExprs,
1997 SrcExprs, AssignmentOps);
1998 }
1999 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2000 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002001 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002002 CGM.getOpenMPRuntime().emitBarrierCall(
2003 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002004 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002005 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002006}
2007
Alexey Bataev8d690652014-12-04 07:23:53 +00002008void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002009 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002010 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2011 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002012 };
2013 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002014}
2015
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002016void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002017 OMPLexicalScope Scope(*this, S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002018 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2019 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002020 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002021 Expr *Hint = nullptr;
2022 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2023 Hint = HintClause->getHint();
2024 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2025 S.getDirectiveName().getAsString(),
2026 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002027}
2028
Alexey Bataev671605e2015-04-13 05:28:11 +00002029void CodeGenFunction::EmitOMPParallelForDirective(
2030 const OMPParallelForDirective &S) {
2031 // Emit directive as a combined directive that consists of two implicit
2032 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002033 OMPLexicalScope Scope(*this, S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002034 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2035 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002036 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002037 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002038}
2039
Alexander Musmane4e893b2014-09-23 09:33:00 +00002040void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002041 const OMPParallelForSimdDirective &S) {
2042 // Emit directive as a combined directive that consists of two implicit
2043 // directives: 'parallel' with 'for' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002044 OMPLexicalScope Scope(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002045 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2046 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002047 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002048 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002049}
2050
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002051void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002052 const OMPParallelSectionsDirective &S) {
2053 // Emit directive as a combined directive that consists of two implicit
2054 // directives: 'parallel' with 'sections' directive.
Alexey Bataev3392d762016-02-16 11:18:12 +00002055 OMPLexicalScope Scope(*this, S);
Alexey Bataev417089f2016-02-17 13:19:37 +00002056 auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002057 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002058}
2059
Alexey Bataev62b63b12015-03-10 07:28:44 +00002060void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2061 // Emit outlined function for task construct.
Alexey Bataev3392d762016-02-16 11:18:12 +00002062 OMPLexicalScope Scope(*this, S);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002063 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2064 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2065 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002066 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002067 // The first function argument for tasks is a thread id, the second one is a
2068 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002069 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2070 // Get list of private variables.
2071 llvm::SmallVector<const Expr *, 8> PrivateVars;
2072 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002073 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002074 auto IRef = C->varlist_begin();
2075 for (auto *IInit : C->private_copies()) {
2076 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2077 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2078 PrivateVars.push_back(*IRef);
2079 PrivateCopies.push_back(IInit);
2080 }
2081 ++IRef;
2082 }
2083 }
2084 EmittedAsPrivate.clear();
2085 // Get list of firstprivate variables.
2086 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
2087 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
2088 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002089 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002090 auto IRef = C->varlist_begin();
2091 auto IElemInitRef = C->inits().begin();
2092 for (auto *IInit : C->private_copies()) {
2093 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2094 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2095 FirstprivateVars.push_back(*IRef);
2096 FirstprivateCopies.push_back(IInit);
2097 FirstprivateInits.push_back(*IElemInitRef);
2098 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002099 ++IRef;
2100 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002101 }
2102 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002103 // Build list of dependences.
2104 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2105 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002106 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002107 for (auto *IRef : C->varlists()) {
2108 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2109 }
2110 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002111 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2112 CodeGenFunction &CGF) {
2113 // Set proper addresses for generated private copies.
2114 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2115 OMPPrivateScope Scope(CGF);
2116 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002117 auto *CopyFn = CGF.Builder.CreateLoad(
2118 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2119 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2120 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002121 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00002122 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002123 PrivatePtrs;
2124 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2125 CallArgs.push_back(PrivatesPtr);
2126 for (auto *E : PrivateVars) {
2127 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002128 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002129 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2130 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002131 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002132 }
2133 for (auto *E : FirstprivateVars) {
2134 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00002135 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002136 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2137 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00002138 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002139 }
2140 CGF.EmitRuntimeCall(CopyFn, CallArgs);
2141 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00002142 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2143 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002144 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2145 }
2146 }
2147 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002148 if (*PartId) {
2149 // TODO: emit code for untied tasks.
2150 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002151 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002152 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002153 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2154 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002155 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002156 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002157 // Check if the task is final
2158 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002159 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002160 // If the condition constant folds and can be elided, try to avoid emitting
2161 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002162 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00002163 bool CondConstant;
2164 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2165 Final.setInt(CondConstant);
2166 else
2167 Final.setPointer(EvaluateExprAsBool(Cond));
2168 } else {
2169 // By default the task is not final.
2170 Final.setInt(/*IntVal=*/false);
2171 }
2172 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002173 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002174 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2175 if (C->getNameModifier() == OMPD_unknown ||
2176 C->getNameModifier() == OMPD_task) {
2177 IfCond = C->getCondition();
2178 break;
2179 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002180 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002181 CGM.getOpenMPRuntime().emitTaskCall(
2182 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002183 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002184 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002185}
2186
Alexey Bataev9f797f32015-02-05 05:57:51 +00002187void CodeGenFunction::EmitOMPTaskyieldDirective(
2188 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002189 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002190}
2191
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002192void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002193 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002194}
2195
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002196void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2197 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002198}
2199
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002200void CodeGenFunction::EmitOMPTaskgroupDirective(
2201 const OMPTaskgroupDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002202 OMPLexicalScope Scope(*this, S);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002203 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2204 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002205 };
2206 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2207}
2208
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002209void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002210 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002211 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002212 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2213 FlushClause->varlist_end());
2214 }
2215 return llvm::None;
2216 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002217}
2218
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002219void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2220 // Emit the loop iteration variable.
2221 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2222 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2223 EmitVarDecl(*IVDecl);
2224
2225 // Emit the iterations count variable.
2226 // If it is not a variable, Sema decided to calculate iterations count on each
2227 // iteration (e.g., it is foldable into a constant).
2228 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2229 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2230 // Emit calculation of the iterations count.
2231 EmitIgnoredExpr(S.getCalcLastIteration());
2232 }
2233
2234 auto &RT = CGM.getOpenMPRuntime();
2235
2236 // Check pre-condition.
2237 {
2238 // Skip the entire loop if we don't meet the precondition.
2239 // If the condition constant folds and can be elided, avoid emitting the
2240 // whole loop.
2241 bool CondConstant;
2242 llvm::BasicBlock *ContBlock = nullptr;
2243 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2244 if (!CondConstant)
2245 return;
2246 } else {
2247 auto *ThenBlock = createBasicBlock("omp.precond.then");
2248 ContBlock = createBasicBlock("omp.precond.end");
2249 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2250 getProfileCount(&S));
2251 EmitBlock(ThenBlock);
2252 incrementProfileCounter(&S);
2253 }
2254
2255 // Emit 'then' code.
2256 {
2257 // Emit helper vars inits.
2258 LValue LB =
2259 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2260 LValue UB =
2261 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2262 LValue ST =
2263 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2264 LValue IL =
2265 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2266
2267 OMPPrivateScope LoopScope(*this);
2268 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
2269 S.private_counters());
2270 (void)LoopScope.Privatize();
2271
2272 // Detect the distribute schedule kind and chunk.
2273 llvm::Value *Chunk = nullptr;
2274 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2275 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2276 ScheduleKind = C->getDistScheduleKind();
2277 if (const auto *Ch = C->getChunkSize()) {
2278 Chunk = EmitScalarExpr(Ch);
2279 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2280 S.getIterationVariable()->getType(),
2281 S.getLocStart());
2282 }
2283 }
2284 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2285 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2286
2287 // OpenMP [2.10.8, distribute Construct, Description]
2288 // If dist_schedule is specified, kind must be static. If specified,
2289 // iterations are divided into chunks of size chunk_size, chunks are
2290 // assigned to the teams of the league in a round-robin fashion in the
2291 // order of the team number. When no chunk_size is specified, the
2292 // iteration space is divided into chunks that are approximately equal
2293 // in size, and at most one chunk is distributed to each team of the
2294 // league. The size of the chunks is unspecified in this case.
2295 if (RT.isStaticNonchunked(ScheduleKind,
2296 /* Chunked */ Chunk != nullptr)) {
2297 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2298 IVSize, IVSigned, /* Ordered = */ false,
2299 IL.getAddress(), LB.getAddress(),
2300 UB.getAddress(), ST.getAddress());
2301 auto LoopExit =
2302 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2303 // UB = min(UB, GlobalUB);
2304 EmitIgnoredExpr(S.getEnsureUpperBound());
2305 // IV = LB;
2306 EmitIgnoredExpr(S.getInit());
2307 // while (idx <= UB) { BODY; ++idx; }
2308 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2309 S.getInc(),
2310 [&S, LoopExit](CodeGenFunction &CGF) {
2311 CGF.EmitOMPLoopBody(S, LoopExit);
2312 CGF.EmitStopPoint(&S);
2313 },
2314 [](CodeGenFunction &) {});
2315 EmitBlock(LoopExit.getBlock());
2316 // Tell the runtime we are done.
2317 RT.emitForStaticFinish(*this, S.getLocStart());
2318 } else {
2319 // Emit the outer loop, which requests its work chunk [LB..UB] from
2320 // runtime and runs the inner loop to process it.
2321 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2322 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2323 IL.getAddress(), Chunk);
2324 }
2325 }
2326
2327 // We're now done with the loop, so jump to the continuation block.
2328 if (ContBlock) {
2329 EmitBranch(ContBlock);
2330 EmitBlock(ContBlock, true);
2331 }
2332 }
2333}
2334
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002335void CodeGenFunction::EmitOMPDistributeDirective(
2336 const OMPDistributeDirective &S) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002337 LexicalScope Scope(*this, S.getSourceRange());
2338 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2339 CGF.EmitOMPDistributeLoop(S);
2340 };
2341 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2342 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002343}
2344
Alexey Bataev5f600d62015-09-29 03:48:57 +00002345static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2346 const CapturedStmt *S) {
2347 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2348 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2349 CGF.CapturedStmtInfo = &CapStmtInfo;
2350 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2351 Fn->addFnAttr(llvm::Attribute::NoInline);
2352 return Fn;
2353}
2354
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002355void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002356 if (!S.getAssociatedStmt())
2357 return;
Alexey Bataev3392d762016-02-16 11:18:12 +00002358 OMPLexicalScope Scope(*this, S);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002359 auto *C = S.getSingleClause<OMPSIMDClause>();
2360 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2361 if (C) {
2362 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2363 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2364 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2365 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2366 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2367 } else {
2368 CGF.EmitStmt(
2369 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2370 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002371 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002372 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002373}
2374
Alexey Bataevb57056f2015-01-22 06:17:56 +00002375static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002376 QualType SrcType, QualType DestType,
2377 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002378 assert(CGF.hasScalarEvaluationKind(DestType) &&
2379 "DestType must have scalar evaluation kind.");
2380 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2381 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002382 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2383 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002384 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002385 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002386}
2387
2388static CodeGenFunction::ComplexPairTy
2389convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002390 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002391 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2392 "DestType must have complex evaluation kind.");
2393 CodeGenFunction::ComplexPairTy ComplexVal;
2394 if (Val.isScalar()) {
2395 // Convert the input element to the element type of the complex.
2396 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002397 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2398 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002399 ComplexVal = CodeGenFunction::ComplexPairTy(
2400 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2401 } else {
2402 assert(Val.isComplex() && "Must be a scalar or complex.");
2403 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2404 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2405 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002406 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002407 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002408 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002409 }
2410 return ComplexVal;
2411}
2412
Alexey Bataev5e018f92015-04-23 06:35:10 +00002413static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2414 LValue LVal, RValue RVal) {
2415 if (LVal.isGlobalReg()) {
2416 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2417 } else {
2418 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2419 : llvm::Monotonic,
2420 LVal.isVolatile(), /*IsInit=*/false);
2421 }
2422}
2423
Alexey Bataev8524d152016-01-21 12:35:58 +00002424void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2425 QualType RValTy, SourceLocation Loc) {
2426 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002427 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002428 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2429 *this, RVal, RValTy, LVal.getType(), Loc)),
2430 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002431 break;
2432 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00002433 EmitStoreOfComplex(
2434 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002435 /*isInit=*/false);
2436 break;
2437 case TEK_Aggregate:
2438 llvm_unreachable("Must be a scalar or complex.");
2439 }
2440}
2441
Alexey Bataevb57056f2015-01-22 06:17:56 +00002442static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2443 const Expr *X, const Expr *V,
2444 SourceLocation Loc) {
2445 // v = x;
2446 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2447 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2448 LValue XLValue = CGF.EmitLValue(X);
2449 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002450 RValue Res = XLValue.isGlobalReg()
2451 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2452 : CGF.EmitAtomicLoad(XLValue, Loc,
2453 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002454 : llvm::Monotonic,
2455 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002456 // OpenMP, 2.12.6, atomic Construct
2457 // Any atomic construct with a seq_cst clause forces the atomically
2458 // performed operation to include an implicit flush operation without a
2459 // list.
2460 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002461 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00002462 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002463}
2464
Alexey Bataevb8329262015-02-27 06:33:30 +00002465static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2466 const Expr *X, const Expr *E,
2467 SourceLocation Loc) {
2468 // x = expr;
2469 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002470 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002471 // OpenMP, 2.12.6, atomic Construct
2472 // Any atomic construct with a seq_cst clause forces the atomically
2473 // performed operation to include an implicit flush operation without a
2474 // list.
2475 if (IsSeqCst)
2476 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2477}
2478
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002479static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2480 RValue Update,
2481 BinaryOperatorKind BO,
2482 llvm::AtomicOrdering AO,
2483 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002484 auto &Context = CGF.CGM.getContext();
2485 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002486 // expression is simple and atomic is allowed for the given type for the
2487 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002488 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002489 !Update.getScalarVal()->getType()->isIntegerTy() ||
2490 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2491 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002492 X.getAddress().getElementType())) ||
2493 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002494 !Context.getTargetInfo().hasBuiltinAtomic(
2495 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002496 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002497
2498 llvm::AtomicRMWInst::BinOp RMWOp;
2499 switch (BO) {
2500 case BO_Add:
2501 RMWOp = llvm::AtomicRMWInst::Add;
2502 break;
2503 case BO_Sub:
2504 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002505 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002506 RMWOp = llvm::AtomicRMWInst::Sub;
2507 break;
2508 case BO_And:
2509 RMWOp = llvm::AtomicRMWInst::And;
2510 break;
2511 case BO_Or:
2512 RMWOp = llvm::AtomicRMWInst::Or;
2513 break;
2514 case BO_Xor:
2515 RMWOp = llvm::AtomicRMWInst::Xor;
2516 break;
2517 case BO_LT:
2518 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2519 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2520 : llvm::AtomicRMWInst::Max)
2521 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2522 : llvm::AtomicRMWInst::UMax);
2523 break;
2524 case BO_GT:
2525 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2526 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2527 : llvm::AtomicRMWInst::Min)
2528 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2529 : llvm::AtomicRMWInst::UMin);
2530 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002531 case BO_Assign:
2532 RMWOp = llvm::AtomicRMWInst::Xchg;
2533 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002534 case BO_Mul:
2535 case BO_Div:
2536 case BO_Rem:
2537 case BO_Shl:
2538 case BO_Shr:
2539 case BO_LAnd:
2540 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002541 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002542 case BO_PtrMemD:
2543 case BO_PtrMemI:
2544 case BO_LE:
2545 case BO_GE:
2546 case BO_EQ:
2547 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002548 case BO_AddAssign:
2549 case BO_SubAssign:
2550 case BO_AndAssign:
2551 case BO_OrAssign:
2552 case BO_XorAssign:
2553 case BO_MulAssign:
2554 case BO_DivAssign:
2555 case BO_RemAssign:
2556 case BO_ShlAssign:
2557 case BO_ShrAssign:
2558 case BO_Comma:
2559 llvm_unreachable("Unsupported atomic update operation");
2560 }
2561 auto *UpdateVal = Update.getScalarVal();
2562 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2563 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002564 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002565 X.getType()->hasSignedIntegerRepresentation());
2566 }
John McCall7f416cc2015-09-08 08:05:57 +00002567 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002568 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002569}
2570
Alexey Bataev5e018f92015-04-23 06:35:10 +00002571std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002572 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2573 llvm::AtomicOrdering AO, SourceLocation Loc,
2574 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2575 // Update expressions are allowed to have the following forms:
2576 // x binop= expr; -> xrval + expr;
2577 // x++, ++x -> xrval + 1;
2578 // x--, --x -> xrval - 1;
2579 // x = x binop expr; -> xrval binop expr
2580 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002581 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2582 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002583 if (X.isGlobalReg()) {
2584 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2585 // 'xrval'.
2586 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2587 } else {
2588 // Perform compare-and-swap procedure.
2589 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002590 }
2591 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002592 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002593}
2594
2595static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2596 const Expr *X, const Expr *E,
2597 const Expr *UE, bool IsXLHSInRHSPart,
2598 SourceLocation Loc) {
2599 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2600 "Update expr in 'atomic update' must be a binary operator.");
2601 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2602 // Update expressions are allowed to have the following forms:
2603 // x binop= expr; -> xrval + expr;
2604 // x++, ++x -> xrval + 1;
2605 // x--, --x -> xrval - 1;
2606 // x = x binop expr; -> xrval binop expr
2607 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002608 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002609 LValue XLValue = CGF.EmitLValue(X);
2610 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002611 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002612 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2613 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2614 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2615 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2616 auto Gen =
2617 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2618 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2619 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2620 return CGF.EmitAnyExpr(UE);
2621 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002622 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2623 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2624 // OpenMP, 2.12.6, atomic Construct
2625 // Any atomic construct with a seq_cst clause forces the atomically
2626 // performed operation to include an implicit flush operation without a
2627 // list.
2628 if (IsSeqCst)
2629 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2630}
2631
2632static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002633 QualType SourceType, QualType ResType,
2634 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002635 switch (CGF.getEvaluationKind(ResType)) {
2636 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002637 return RValue::get(
2638 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002639 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002640 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002641 return RValue::getComplex(Res.first, Res.second);
2642 }
2643 case TEK_Aggregate:
2644 break;
2645 }
2646 llvm_unreachable("Must be a scalar or complex.");
2647}
2648
2649static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2650 bool IsPostfixUpdate, const Expr *V,
2651 const Expr *X, const Expr *E,
2652 const Expr *UE, bool IsXLHSInRHSPart,
2653 SourceLocation Loc) {
2654 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2655 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2656 RValue NewVVal;
2657 LValue VLValue = CGF.EmitLValue(V);
2658 LValue XLValue = CGF.EmitLValue(X);
2659 RValue ExprRValue = CGF.EmitAnyExpr(E);
2660 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2661 QualType NewVValType;
2662 if (UE) {
2663 // 'x' is updated with some additional value.
2664 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2665 "Update expr in 'atomic capture' must be a binary operator.");
2666 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2667 // Update expressions are allowed to have the following forms:
2668 // x binop= expr; -> xrval + expr;
2669 // x++, ++x -> xrval + 1;
2670 // x--, --x -> xrval - 1;
2671 // x = x binop expr; -> xrval binop expr
2672 // x = expr Op x; - > expr binop xrval;
2673 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2674 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2675 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2676 NewVValType = XRValExpr->getType();
2677 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2678 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2679 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2680 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2681 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2682 RValue Res = CGF.EmitAnyExpr(UE);
2683 NewVVal = IsPostfixUpdate ? XRValue : Res;
2684 return Res;
2685 };
2686 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2687 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2688 if (Res.first) {
2689 // 'atomicrmw' instruction was generated.
2690 if (IsPostfixUpdate) {
2691 // Use old value from 'atomicrmw'.
2692 NewVVal = Res.second;
2693 } else {
2694 // 'atomicrmw' does not provide new value, so evaluate it using old
2695 // value of 'x'.
2696 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2697 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2698 NewVVal = CGF.EmitAnyExpr(UE);
2699 }
2700 }
2701 } else {
2702 // 'x' is simply rewritten with some 'expr'.
2703 NewVValType = X->getType().getNonReferenceType();
2704 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002705 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002706 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2707 NewVVal = XRValue;
2708 return ExprRValue;
2709 };
2710 // Try to perform atomicrmw xchg, otherwise simple exchange.
2711 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2712 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2713 Loc, Gen);
2714 if (Res.first) {
2715 // 'atomicrmw' instruction was generated.
2716 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2717 }
2718 }
2719 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00002720 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002721 // OpenMP, 2.12.6, atomic Construct
2722 // Any atomic construct with a seq_cst clause forces the atomically
2723 // performed operation to include an implicit flush operation without a
2724 // list.
2725 if (IsSeqCst)
2726 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2727}
2728
Alexey Bataevb57056f2015-01-22 06:17:56 +00002729static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002730 bool IsSeqCst, bool IsPostfixUpdate,
2731 const Expr *X, const Expr *V, const Expr *E,
2732 const Expr *UE, bool IsXLHSInRHSPart,
2733 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002734 switch (Kind) {
2735 case OMPC_read:
2736 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2737 break;
2738 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002739 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2740 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002741 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002742 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002743 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2744 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002745 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002746 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2747 IsXLHSInRHSPart, Loc);
2748 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002749 case OMPC_if:
2750 case OMPC_final:
2751 case OMPC_num_threads:
2752 case OMPC_private:
2753 case OMPC_firstprivate:
2754 case OMPC_lastprivate:
2755 case OMPC_reduction:
2756 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002757 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002758 case OMPC_collapse:
2759 case OMPC_default:
2760 case OMPC_seq_cst:
2761 case OMPC_shared:
2762 case OMPC_linear:
2763 case OMPC_aligned:
2764 case OMPC_copyin:
2765 case OMPC_copyprivate:
2766 case OMPC_flush:
2767 case OMPC_proc_bind:
2768 case OMPC_schedule:
2769 case OMPC_ordered:
2770 case OMPC_nowait:
2771 case OMPC_untied:
2772 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002773 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002774 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002775 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002776 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002777 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002778 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002779 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002780 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002781 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002782 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00002783 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00002784 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00002785 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00002786 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00002787 case OMPC_defaultmap:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002788 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2789 }
2790}
2791
2792void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002793 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002794 OpenMPClauseKind Kind = OMPC_unknown;
2795 for (auto *C : S.clauses()) {
2796 // Find first clause (skip seq_cst clause, if it is first).
2797 if (C->getClauseKind() != OMPC_seq_cst) {
2798 Kind = C->getClauseKind();
2799 break;
2800 }
2801 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002802
2803 const auto *CS =
2804 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002805 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002806 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002807 }
2808 // Processing for statements under 'atomic capture'.
2809 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2810 for (const auto *C : Compound->body()) {
2811 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2812 enterFullExpression(EWC);
2813 }
2814 }
2815 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002816
Alexey Bataev3392d762016-02-16 11:18:12 +00002817 OMPLexicalScope Scope(*this, S);
Alexey Bataev33c56402015-12-14 09:26:19 +00002818 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2819 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002820 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2821 S.getV(), S.getExpr(), S.getUpdateExpr(),
2822 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002823 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002824 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002825}
2826
Samuel Antaobed3c462015-10-02 16:14:20 +00002827void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002828 OMPLexicalScope Scope(*this, S);
Samuel Antaobed3c462015-10-02 16:14:20 +00002829 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2830
2831 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00002832 GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00002833
Samuel Antaoee8fb302016-01-06 13:42:12 +00002834 llvm::Function *Fn = nullptr;
2835 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00002836
2837 // Check if we have any if clause associated with the directive.
2838 const Expr *IfCond = nullptr;
2839
2840 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2841 IfCond = C->getCondition();
2842 }
2843
2844 // Check if we have any device clause associated with the directive.
2845 const Expr *Device = nullptr;
2846 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2847 Device = C->getDevice();
2848 }
2849
Samuel Antaoee8fb302016-01-06 13:42:12 +00002850 // Check if we have an if clause whose conditional always evaluates to false
2851 // or if we do not have any targets specified. If so the target region is not
2852 // an offload entry point.
2853 bool IsOffloadEntry = true;
2854 if (IfCond) {
2855 bool Val;
2856 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2857 IsOffloadEntry = false;
2858 }
2859 if (CGM.getLangOpts().OMPTargetTriples.empty())
2860 IsOffloadEntry = false;
2861
2862 assert(CurFuncDecl && "No parent declaration for target region!");
2863 StringRef ParentName;
2864 // In case we have Ctors/Dtors we use the complete type variant to produce
2865 // the mangling of the device outlined kernel.
2866 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2867 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2868 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2869 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2870 else
2871 ParentName =
2872 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2873
2874 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2875 IsOffloadEntry);
2876
2877 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00002878 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002879}
2880
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002881static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
2882 const OMPExecutableDirective &S,
2883 OpenMPDirectiveKind InnermostKind,
2884 const RegionCodeGenTy &CodeGen) {
2885 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2886 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2887 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2888 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
2889 emitParallelOrTeamsOutlinedFunction(S,
2890 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00002891
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002892 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
2893 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
2894 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
2895 if (NT || TL) {
2896 llvm::Value *NumTeamsVal = (NT) ? CGF.Builder.CreateIntCast(
2897 CGF.EmitScalarExpr(NT->getNumTeams()), CGF.CGM.Int32Ty,
2898 /* isSigned = */ true) :
2899 CGF.Builder.getInt32(0);
2900
2901 llvm::Value *ThreadLimitVal = (TL) ? CGF.Builder.CreateIntCast(
2902 CGF.EmitScalarExpr(TL->getThreadLimit()), CGF.CGM.Int32Ty,
2903 /* isSigned = */ true) :
2904 CGF.Builder.getInt32(0);
2905
2906 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeamsVal,
2907 ThreadLimitVal, S.getLocStart());
2908 }
2909
2910 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
2911 CapturedVars);
2912}
2913
2914void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
2915 LexicalScope Scope(*this, S.getSourceRange());
2916 // Emit parallel region as a standalone region.
2917 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2918 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00002919 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
2920 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002921 (void)PrivateScope.Privatize();
2922 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2923 };
2924 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002925}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002926
2927void CodeGenFunction::EmitOMPCancellationPointDirective(
2928 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002929 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2930 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002931}
2932
Alexey Bataev80909872015-07-02 11:25:17 +00002933void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002934 const Expr *IfCond = nullptr;
2935 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2936 if (C->getNameModifier() == OMPD_unknown ||
2937 C->getNameModifier() == OMPD_cancel) {
2938 IfCond = C->getCondition();
2939 break;
2940 }
2941 }
2942 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002943 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002944}
2945
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002946CodeGenFunction::JumpDest
2947CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2948 if (Kind == OMPD_parallel || Kind == OMPD_task)
2949 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002950 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002951 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002952 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002953}
Michael Wong65f367f2015-07-21 13:44:28 +00002954
2955// Generate the instructions for '#pragma omp target data' directive.
2956void CodeGenFunction::EmitOMPTargetDataDirective(
2957 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002958 // emit the code inside the construct for now
2959 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002960 CGM.getOpenMPRuntime().emitInlinedDirective(
2961 *this, OMPD_target_data,
2962 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002963}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002964
Samuel Antaodf67fc42016-01-19 19:15:56 +00002965void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2966 const OMPTargetEnterDataDirective &S) {
2967 // TODO: codegen for target enter data.
2968}
2969
Samuel Antao72590762016-01-19 20:04:50 +00002970void CodeGenFunction::EmitOMPTargetExitDataDirective(
2971 const OMPTargetExitDataDirective &S) {
2972 // TODO: codegen for target exit data.
2973}
2974
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002975void CodeGenFunction::EmitOMPTargetParallelDirective(
2976 const OMPTargetParallelDirective &S) {
2977 // TODO: codegen for target parallel.
2978}
2979
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002980void CodeGenFunction::EmitOMPTargetParallelForDirective(
2981 const OMPTargetParallelForDirective &S) {
2982 // TODO: codegen for target parallel for.
2983}
2984
Alexey Bataev49f6e782015-12-01 04:18:41 +00002985void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2986 // emit the code inside the construct for now
2987 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2988 CGM.getOpenMPRuntime().emitInlinedDirective(
2989 *this, OMPD_taskloop,
2990 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2991}
2992
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002993void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2994 const OMPTaskLoopSimdDirective &S) {
2995 // emit the code inside the construct for now
2996 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2997 CGM.getOpenMPRuntime().emitInlinedDirective(
2998 *this, OMPD_taskloop_simd,
2999 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
3000}
3001