blob: c76835f02ebbcd181e44ec467e34eadabecadcc5 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000057 bool AsInlined = false, bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000058 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000060 if (EmitPreInitStmt)
61 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000062 if (AsInlined) {
63 if (S.hasAssociatedStmt()) {
64 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65 for (auto &C : CS->captures()) {
66 if (C.capturesVariable() || C.capturesVariableByCopy()) {
67 auto *VD = C.getCapturedVar();
68 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
69 isCapturedVar(CGF, VD) ||
70 (CGF.CapturedStmtInfo &&
71 InlinedShareds.isGlobalVarCaptured(VD)),
72 VD->getType().getNonReferenceType(), VK_LValue,
73 SourceLocation());
74 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
75 return CGF.EmitLValue(&DRE).getAddress();
76 });
77 }
78 }
79 (void)InlinedShareds.Privatize();
80 }
81 }
Alexey Bataev3392d762016-02-16 11:18:12 +000082 }
83};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000084
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000085/// Lexical scope for OpenMP parallel construct, that handles correct codegen
86/// for captured expressions.
87class OMPParallelScope final : public OMPLexicalScope {
88 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
89 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000090 return !(isOpenMPTargetExecutionDirective(Kind) ||
91 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000092 isOpenMPParallelDirective(Kind);
93 }
94
95public:
96 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
97 : OMPLexicalScope(CGF, S,
98 /*AsInlined=*/false,
99 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
100};
101
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000102/// Lexical scope for OpenMP teams construct, that handles correct codegen
103/// for captured expressions.
104class OMPTeamsScope final : public OMPLexicalScope {
105 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
106 OpenMPDirectiveKind Kind = S.getDirectiveKind();
107 return !isOpenMPTargetExecutionDirective(Kind) &&
108 isOpenMPTeamsDirective(Kind);
109 }
110
111public:
112 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
113 : OMPLexicalScope(CGF, S,
114 /*AsInlined=*/false,
115 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
116};
117
Alexey Bataev5a3af132016-03-29 08:58:54 +0000118/// Private scope for OpenMP loop-based directives, that supports capturing
119/// of used expression from loop statement.
120class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
121 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
122 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
123 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
124 for (const auto *I : PreInits->decls())
125 CGF.EmitVarDecl(cast<VarDecl>(*I));
126 }
127 }
128 }
129
130public:
131 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
132 : CodeGenFunction::RunCleanupsScope(CGF) {
133 emitPreInitStmt(CGF, S);
134 }
135};
136
Alexey Bataev3392d762016-02-16 11:18:12 +0000137} // namespace
138
Alexey Bataev1189bd02016-01-26 12:20:39 +0000139llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
140 auto &C = getContext();
141 llvm::Value *Size = nullptr;
142 auto SizeInChars = C.getTypeSizeInChars(Ty);
143 if (SizeInChars.isZero()) {
144 // getTypeSizeInChars() returns 0 for a VLA.
145 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
146 llvm::Value *ArraySize;
147 std::tie(ArraySize, Ty) = getVLASize(VAT);
148 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
149 }
150 SizeInChars = C.getTypeSizeInChars(Ty);
151 if (SizeInChars.isZero())
152 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
153 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
154 } else
155 Size = CGM.getSize(SizeInChars);
156 return Size;
157}
158
Alexey Bataev2377fe92015-09-10 08:12:02 +0000159void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000160 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000161 const RecordDecl *RD = S.getCapturedRecordDecl();
162 auto CurField = RD->field_begin();
163 auto CurCap = S.captures().begin();
164 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
165 E = S.capture_init_end();
166 I != E; ++I, ++CurField, ++CurCap) {
167 if (CurField->hasCapturedVLAType()) {
168 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000169 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000170 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000171 } else if (CurCap->capturesThis())
172 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000173 else if (CurCap->capturesVariableByCopy()) {
174 llvm::Value *CV =
175 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
176
177 // If the field is not a pointer, we need to save the actual value
178 // and load it as a void pointer.
179 if (!CurField->getType()->isAnyPointerType()) {
180 auto &Ctx = getContext();
181 auto DstAddr = CreateMemTemp(
182 Ctx.getUIntPtrType(),
183 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
184 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
185
186 auto *SrcAddrVal = EmitScalarConversion(
187 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
188 Ctx.getPointerType(CurField->getType()), SourceLocation());
189 LValue SrcLV =
190 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
191
192 // Store the value using the source type pointer.
193 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
194
195 // Load the value using the destination type pointer.
196 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
197 }
198 CapturedVars.push_back(CV);
199 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000200 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000201 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000202 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000203 }
204}
205
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
207 StringRef Name, LValue AddrLV,
208 bool isReferenceType = false) {
209 ASTContext &Ctx = CGF.getContext();
210
211 auto *CastedPtr = CGF.EmitScalarConversion(
212 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
213 Ctx.getPointerType(DstType), SourceLocation());
214 auto TmpAddr =
215 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
216 .getAddress();
217
218 // If we are dealing with references we need to return the address of the
219 // reference instead of the reference of the value.
220 if (isReferenceType) {
221 QualType RefType = Ctx.getLValueReferenceType(DstType);
222 auto *RefVal = TmpAddr.getPointer();
223 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
224 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000225 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000226 }
227
228 return TmpAddr;
229}
230
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000231static QualType getCanonicalParamType(ASTContext &C, QualType T) {
232 if (T->isLValueReferenceType()) {
233 return C.getLValueReferenceType(
234 getCanonicalParamType(C, T.getNonReferenceType()),
235 /*SpelledAsLValue=*/false);
236 }
237 if (T->isPointerType())
238 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
239 return C.getCanonicalParamType(T);
240}
241
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000242namespace {
243 /// Contains required data for proper outlined function codegen.
244 struct FunctionOptions {
245 /// Captured statement for which the function is generated.
246 const CapturedStmt *S = nullptr;
247 /// true if cast to/from UIntPtr is required for variables captured by
248 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000249 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000250 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000251 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000252 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000253 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000254 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000255 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
256 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000257 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000258 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
259 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000260 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000261 };
262}
263
Alexey Bataeve754b182017-08-09 19:38:53 +0000264static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000265 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000266 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000267 &LocalAddrs,
268 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
269 &VLASizes,
270 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
271 const CapturedDecl *CD = FO.S->getCapturedDecl();
272 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000273 assert(CD->hasBody() && "missing CapturedDecl body");
274
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000275 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000276 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000277 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000278 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000279 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000280 Args.append(CD->param_begin(),
281 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000282 TargetArgs.append(
283 CD->param_begin(),
284 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000285 auto I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000286 for (auto *FD : RD->fields()) {
287 QualType ArgType = FD->getType();
288 IdentifierInfo *II = nullptr;
289 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000290
291 // If this is a capture by copy and the type is not a pointer, the outlined
292 // function argument type should be uintptr and the value properly casted to
293 // uintptr. This is necessary given that the runtime library is only able to
294 // deal with pointers. We can pass in the same way the VLA type sizes to the
295 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000296 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000297 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000298 if (FO.UIntPtrCastRequired)
299 ArgType = Ctx.getUIntPtrType();
300 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000301
302 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000303 CapVar = I->getCapturedVar();
304 II = CapVar->getIdentifier();
305 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000306 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000307 else {
308 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000309 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000310 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000311 if (ArgType->isVariablyModifiedType())
312 ArgType = getCanonicalParamType(Ctx, ArgType.getNonReferenceType());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000313 auto *Arg =
314 ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), II,
315 ArgType, ImplicitParamDecl::Other);
316 Args.emplace_back(Arg);
317 // Do not cast arguments if we emit function with non-original types.
318 TargetArgs.emplace_back(
319 FO.UIntPtrCastRequired
320 ? Arg
321 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000322 ++I;
323 }
324 Args.append(
325 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
326 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000327 TargetArgs.append(
328 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
329 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000330
331 // Create the function declaration.
332 FunctionType::ExtInfo ExtInfo;
333 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000334 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000335 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
336
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000337 llvm::Function *F =
338 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
339 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000340 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
341 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000342 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000343
344 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000345 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
346 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000347 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000348 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000349 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000350 // Do not map arguments if we emit function with non-original types.
351 Address LocalAddr(Address::invalid());
352 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
353 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
354 TargetArgs[Cnt]);
355 } else {
356 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
357 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000358 // If we are capturing a pointer by copy we don't need to do anything, just
359 // use the value that we get from the arguments.
360 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000361 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000362 // If the variable is a reference we need to materialize it here.
363 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000364 Address RefAddr = CGF.CreateMemTemp(
365 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
366 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
367 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000368 LocalAddr = RefAddr;
369 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000370 if (!FO.RegisterCastedArgsOnly)
371 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000372 ++Cnt;
373 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000374 continue;
375 }
376
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000377 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000378 LValue ArgLVal =
379 CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(), BaseInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000380 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000381 if (FO.UIntPtrCastRequired) {
382 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
383 Args[Cnt]->getName(),
384 ArgLVal),
385 FD->getType(), BaseInfo);
386 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000387 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000388 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000389 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000390 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000391 } else if (I->capturesVariable()) {
392 auto *Var = I->getCapturedVar();
393 QualType VarTy = Var->getType();
394 Address ArgAddr = ArgLVal.getAddress();
395 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000396 if (ArgLVal.getType()->isLValueReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000397 ArgAddr = CGF.EmitLoadOfReference(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000398 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000399 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000400 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000401 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000402 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
403 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000404 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000405 if (!FO.RegisterCastedArgsOnly) {
406 LocalAddrs.insert(
407 {Args[Cnt],
408 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
409 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000410 } else if (I->capturesVariableByCopy()) {
411 assert(!FD->getType()->isAnyPointerType() &&
412 "Not expecting a captured pointer.");
413 auto *Var = I->getCapturedVar();
414 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000415 LocalAddrs.insert(
416 {Args[Cnt],
417 {Var,
418 FO.UIntPtrCastRequired
419 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
420 ArgLVal, VarTy->isReferenceType())
421 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000422 } else {
423 // If 'this' is captured, load it into CXXThisValue.
424 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000425 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
426 .getScalarVal();
427 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000428 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000429 ++Cnt;
430 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000431 }
432
Alexey Bataeve754b182017-08-09 19:38:53 +0000433 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000434}
435
436llvm::Function *
437CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
438 assert(
439 CapturedStmtInfo &&
440 "CapturedStmtInfo should be set when generating the captured function");
441 const CapturedDecl *CD = S.getCapturedDecl();
442 // Build the argument list.
443 bool NeedWrapperFunction =
444 getDebugInfo() &&
445 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
446 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000447 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000448 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000449 SmallString<256> Buffer;
450 llvm::raw_svector_ostream Out(Buffer);
451 Out << CapturedStmtInfo->getHelperName();
452 if (NeedWrapperFunction)
453 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000454 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000455 Out.str());
456 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
457 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000458 for (const auto &LocalAddrPair : LocalAddrs) {
459 if (LocalAddrPair.second.first) {
460 setAddrOfLocalVar(LocalAddrPair.second.first,
461 LocalAddrPair.second.second);
462 }
463 }
464 for (const auto &VLASizePair : VLASizes)
465 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000466 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000467 CapturedStmtInfo->EmitBody(*this, CD->getBody());
468 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000469 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000470 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000471
Alexey Bataevefd884d2017-08-04 21:26:25 +0000472 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000473 /*RegisterCastedArgsOnly=*/true,
474 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000475 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000476 Args.clear();
477 LocalAddrs.clear();
478 VLASizes.clear();
479 llvm::Function *WrapperF =
480 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000481 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000482 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
483 llvm::SmallVector<llvm::Value *, 4> CallArgs;
484 for (const auto *Arg : Args) {
485 llvm::Value *CallArg;
486 auto I = LocalAddrs.find(Arg);
487 if (I != LocalAddrs.end()) {
488 LValue LV =
489 WrapperCGF.MakeAddrLValue(I->second.second, Arg->getType(), BaseInfo);
490 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
491 } else {
492 auto EI = VLASizes.find(Arg);
493 if (EI != VLASizes.end())
494 CallArg = EI->second.second;
495 else {
496 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
497 Arg->getType(), BaseInfo);
498 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
499 }
500 }
501 CallArgs.emplace_back(CallArg);
502 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000503 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
504 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000505 WrapperCGF.FinishFunction();
506 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507}
508
Alexey Bataev9959db52014-05-06 10:08:46 +0000509//===----------------------------------------------------------------------===//
510// OpenMP Directive Emission
511//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000512void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000513 Address DestAddr, Address SrcAddr, QualType OriginalType,
514 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000515 // Perform element-by-element initialization.
516 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000517
518 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000519 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000520 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
521 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
522
523 auto SrcBegin = SrcAddr.getPointer();
524 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000525 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000526 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
527 // The basic structure here is a while-do loop.
528 auto BodyBB = createBasicBlock("omp.arraycpy.body");
529 auto DoneBB = createBasicBlock("omp.arraycpy.done");
530 auto IsEmpty =
531 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
532 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000533
Alexey Bataev420d45b2015-04-14 05:11:24 +0000534 // Enter the loop body, making that address the current address.
535 auto EntryBB = Builder.GetInsertBlock();
536 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000537
538 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
539
540 llvm::PHINode *SrcElementPHI =
541 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
542 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
543 Address SrcElementCurrent =
544 Address(SrcElementPHI,
545 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
546
547 llvm::PHINode *DestElementPHI =
548 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
549 DestElementPHI->addIncoming(DestBegin, EntryBB);
550 Address DestElementCurrent =
551 Address(DestElementPHI,
552 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000553
Alexey Bataev420d45b2015-04-14 05:11:24 +0000554 // Emit copy.
555 CopyGen(DestElementCurrent, SrcElementCurrent);
556
557 // Shift the address forward by one element.
558 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000559 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000560 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000561 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000562 // Check whether we've reached the end.
563 auto Done =
564 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
565 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000566 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
567 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000568
569 // Done.
570 EmitBlock(DoneBB, /*IsFinished=*/true);
571}
572
John McCall7f416cc2015-09-08 08:05:57 +0000573void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
574 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000575 const VarDecl *SrcVD, const Expr *Copy) {
576 if (OriginalType->isArrayType()) {
577 auto *BO = dyn_cast<BinaryOperator>(Copy);
578 if (BO && BO->getOpcode() == BO_Assign) {
579 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000580 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000581 } else {
582 // For arrays with complex element types perform element by element
583 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000584 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000585 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000586 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000587 // Working with the single array element, so have to remap
588 // destination and source variables to corresponding array
589 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000590 CodeGenFunction::OMPPrivateScope Remap(*this);
591 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000592 return DestElement;
593 });
594 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000595 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000596 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000597 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000598 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000599 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000600 } else {
601 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000602 CodeGenFunction::OMPPrivateScope Remap(*this);
603 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
604 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000605 (void)Remap.Privatize();
606 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000607 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000608 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000609}
610
Alexey Bataev69c62a92015-04-15 04:52:20 +0000611bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
612 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000613 if (!HaveInsertPoint())
614 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000615 bool FirstprivateIsLastprivate = false;
616 llvm::DenseSet<const VarDecl *> Lastprivates;
617 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
618 for (const auto *D : C->varlists())
619 Lastprivates.insert(
620 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
621 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000622 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000623 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000624 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000625 auto IRef = C->varlist_begin();
626 auto InitsRef = C->inits().begin();
627 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000628 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000629 bool ThisFirstprivateIsLastprivate =
630 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000631 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000632 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000633 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000634 !FD->getType()->isReferenceType()) {
635 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
636 ++IRef;
637 ++InitsRef;
638 continue;
639 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000640 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000641 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000642 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000643 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
644 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
645 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000646 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
647 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
648 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000649 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000650 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000651 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000652 // Emit VarDecl with copy init for arrays.
653 // Get the address of the original variable captured in current
654 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000655 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000656 auto Emission = EmitAutoVarAlloca(*VD);
657 auto *Init = VD->getInit();
658 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
659 // Perform simple memcpy.
660 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000661 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000662 } else {
663 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000664 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000665 [this, VDInit, Init](Address DestElement,
666 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000667 // Clean up any temporaries needed by the initialization.
668 RunCleanupsScope InitScope(*this);
669 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000670 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000671 EmitAnyExprToMem(Init, DestElement,
672 Init->getType().getQualifiers(),
673 /*IsInitializer*/ false);
674 LocalDeclMap.erase(VDInit);
675 });
676 }
677 EmitAutoVarCleanups(Emission);
678 return Emission.getAllocatedAddress();
679 });
680 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000681 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000682 // Emit private VarDecl with copy init.
683 // Remap temp VDInit variable to the address of the original
684 // variable
685 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000686 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000687 EmitDecl(*VD);
688 LocalDeclMap.erase(VDInit);
689 return GetAddrOfLocalVar(VD);
690 });
691 }
692 assert(IsRegistered &&
693 "firstprivate var already registered as private");
694 // Silence the warning about unused variable.
695 (void)IsRegistered;
696 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000697 ++IRef;
698 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000699 }
700 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000701 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000702}
703
Alexey Bataev03b340a2014-10-21 03:16:40 +0000704void CodeGenFunction::EmitOMPPrivateClause(
705 const OMPExecutableDirective &D,
706 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000707 if (!HaveInsertPoint())
708 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000709 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000710 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000711 auto IRef = C->varlist_begin();
712 for (auto IInit : C->private_copies()) {
713 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000714 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
715 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
716 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000717 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000718 // Emit private VarDecl with copy init.
719 EmitDecl(*VD);
720 return GetAddrOfLocalVar(VD);
721 });
722 assert(IsRegistered && "private var already registered as private");
723 // Silence the warning about unused variable.
724 (void)IsRegistered;
725 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000726 ++IRef;
727 }
728 }
729}
730
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000731bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000732 if (!HaveInsertPoint())
733 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000734 // threadprivate_var1 = master_threadprivate_var1;
735 // operator=(threadprivate_var2, master_threadprivate_var2);
736 // ...
737 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000738 llvm::DenseSet<const VarDecl *> CopiedVars;
739 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000740 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000741 auto IRef = C->varlist_begin();
742 auto ISrcRef = C->source_exprs().begin();
743 auto IDestRef = C->destination_exprs().begin();
744 for (auto *AssignOp : C->assignment_ops()) {
745 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000746 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000747 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000748 // Get the address of the master variable. If we are emitting code with
749 // TLS support, the address is passed from the master as field in the
750 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000751 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000752 if (getLangOpts().OpenMPUseTLS &&
753 getContext().getTargetInfo().isTLSSupported()) {
754 assert(CapturedStmtInfo->lookup(VD) &&
755 "Copyin threadprivates should have been captured!");
756 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
757 VK_LValue, (*IRef)->getExprLoc());
758 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000759 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000760 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000761 MasterAddr =
762 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
763 : CGM.GetAddrOfGlobal(VD),
764 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000765 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000766 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000767 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000768 if (CopiedVars.size() == 1) {
769 // At first check if current thread is a master thread. If it is, no
770 // need to copy data.
771 CopyBegin = createBasicBlock("copyin.not.master");
772 CopyEnd = createBasicBlock("copyin.not.master.end");
773 Builder.CreateCondBr(
774 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000775 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
776 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000777 CopyBegin, CopyEnd);
778 EmitBlock(CopyBegin);
779 }
780 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
781 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000782 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000783 }
784 ++IRef;
785 ++ISrcRef;
786 ++IDestRef;
787 }
788 }
789 if (CopyEnd) {
790 // Exit out of copying procedure for non-master thread.
791 EmitBlock(CopyEnd, /*IsFinished=*/true);
792 return true;
793 }
794 return false;
795}
796
Alexey Bataev38e89532015-04-16 04:54:05 +0000797bool CodeGenFunction::EmitOMPLastprivateClauseInit(
798 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000799 if (!HaveInsertPoint())
800 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000801 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000802 llvm::DenseSet<const VarDecl *> SIMDLCVs;
803 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
804 auto *LoopDirective = cast<OMPLoopDirective>(&D);
805 for (auto *C : LoopDirective->counters()) {
806 SIMDLCVs.insert(
807 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
808 }
809 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000810 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000811 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000812 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000813 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
814 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000815 auto IRef = C->varlist_begin();
816 auto IDestRef = C->destination_exprs().begin();
817 for (auto *IInit : C->private_copies()) {
818 // Keep the address of the original variable for future update at the end
819 // of the loop.
820 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000821 // Taskloops do not require additional initialization, it is done in
822 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000823 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
824 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000825 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000826 DeclRefExpr DRE(
827 const_cast<VarDecl *>(OrigVD),
828 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
829 OrigVD) != nullptr,
830 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
831 return EmitLValue(&DRE).getAddress();
832 });
833 // Check if the variable is also a firstprivate: in this case IInit is
834 // not generated. Initialization of this variable will happen in codegen
835 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000836 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000837 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000838 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
839 // Emit private VarDecl with copy init.
840 EmitDecl(*VD);
841 return GetAddrOfLocalVar(VD);
842 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000843 assert(IsRegistered &&
844 "lastprivate var already registered as private");
845 (void)IsRegistered;
846 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000847 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000848 ++IRef;
849 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000850 }
851 }
852 return HasAtLeastOneLastprivate;
853}
854
855void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000856 const OMPExecutableDirective &D, bool NoFinals,
857 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000858 if (!HaveInsertPoint())
859 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000860 // Emit following code:
861 // if (<IsLastIterCond>) {
862 // orig_var1 = private_orig_var1;
863 // ...
864 // orig_varn = private_orig_varn;
865 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000866 llvm::BasicBlock *ThenBB = nullptr;
867 llvm::BasicBlock *DoneBB = nullptr;
868 if (IsLastIterCond) {
869 ThenBB = createBasicBlock(".omp.lastprivate.then");
870 DoneBB = createBasicBlock(".omp.lastprivate.done");
871 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
872 EmitBlock(ThenBB);
873 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000874 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
875 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000876 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000877 auto IC = LoopDirective->counters().begin();
878 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000879 auto *D =
880 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
881 if (NoFinals)
882 AlreadyEmittedVars.insert(D);
883 else
884 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000885 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000886 }
887 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000888 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
889 auto IRef = C->varlist_begin();
890 auto ISrcRef = C->source_exprs().begin();
891 auto IDestRef = C->destination_exprs().begin();
892 for (auto *AssignOp : C->assignment_ops()) {
893 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
894 QualType Type = PrivateVD->getType();
895 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
896 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
897 // If lastprivate variable is a loop control variable for loop-based
898 // directive, update its value before copyin back to original
899 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000900 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
901 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000902 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
903 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
904 // Get the address of the original variable.
905 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
906 // Get the address of the private variable.
907 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
908 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
909 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000910 Address(Builder.CreateLoad(PrivateAddr),
911 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000912 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000913 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000914 ++IRef;
915 ++ISrcRef;
916 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000917 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000918 if (auto *PostUpdate = C->getPostUpdateExpr())
919 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000920 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000921 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000922 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000923}
924
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000925void CodeGenFunction::EmitOMPReductionClauseInit(
926 const OMPExecutableDirective &D,
927 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000928 if (!HaveInsertPoint())
929 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000930 SmallVector<const Expr *, 4> Shareds;
931 SmallVector<const Expr *, 4> Privates;
932 SmallVector<const Expr *, 4> ReductionOps;
933 SmallVector<const Expr *, 4> LHSs;
934 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000935 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000936 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000937 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000938 auto ILHS = C->lhs_exprs().begin();
939 auto IRHS = C->rhs_exprs().begin();
940 for (const auto *Ref : C->varlists()) {
941 Shareds.emplace_back(Ref);
942 Privates.emplace_back(*IPriv);
943 ReductionOps.emplace_back(*IRed);
944 LHSs.emplace_back(*ILHS);
945 RHSs.emplace_back(*IRHS);
946 std::advance(IPriv, 1);
947 std::advance(IRed, 1);
948 std::advance(ILHS, 1);
949 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000950 }
951 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
953 unsigned Count = 0;
954 auto ILHS = LHSs.begin();
955 auto IRHS = RHSs.begin();
956 auto IPriv = Privates.begin();
957 for (const auto *IRef : Shareds) {
958 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
959 // Emit private VarDecl with reduction init.
960 RedCG.emitSharedLValue(*this, Count);
961 RedCG.emitAggregateType(*this, Count);
962 auto Emission = EmitAutoVarAlloca(*PrivateVD);
963 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
964 RedCG.getSharedLValue(Count),
965 [&Emission](CodeGenFunction &CGF) {
966 CGF.EmitAutoVarInit(Emission);
967 return true;
968 });
969 EmitAutoVarCleanups(Emission);
970 Address BaseAddr = RedCG.adjustPrivateAddress(
971 *this, Count, Emission.getAllocatedAddress());
972 bool IsRegistered = PrivateScope.addPrivate(
973 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
974 assert(IsRegistered && "private var already registered as private");
975 // Silence the warning about unused variable.
976 (void)IsRegistered;
977
978 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
979 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Eric Christopher7aba9782017-07-14 01:42:57 +0000980 if (isa<OMPArraySectionExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 // Store the address of the original variable associated with the LHS
982 // implicit variable.
983 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
984 return RedCG.getSharedLValue(Count).getAddress();
985 });
986 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
987 return GetAddrOfLocalVar(PrivateVD);
988 });
Eric Christopher7aba9782017-07-14 01:42:57 +0000989 } else if (isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000990 // Store the address of the original variable associated with the LHS
991 // implicit variable.
992 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
993 return RedCG.getSharedLValue(Count).getAddress();
994 });
995 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
996 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
997 ConvertTypeForMem(RHSVD->getType()),
998 "rhs.begin");
999 });
1000 } else {
1001 QualType Type = PrivateVD->getType();
1002 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1003 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1004 // Store the address of the original variable associated with the LHS
1005 // implicit variable.
1006 if (IsArray) {
1007 OriginalAddr = Builder.CreateElementBitCast(
1008 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1009 }
1010 PrivateScope.addPrivate(
1011 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1012 PrivateScope.addPrivate(
1013 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1014 return IsArray
1015 ? Builder.CreateElementBitCast(
1016 GetAddrOfLocalVar(PrivateVD),
1017 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1018 : GetAddrOfLocalVar(PrivateVD);
1019 });
1020 }
1021 ++ILHS;
1022 ++IRHS;
1023 ++IPriv;
1024 ++Count;
1025 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001026}
1027
1028void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001029 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001030 if (!HaveInsertPoint())
1031 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001032 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001033 llvm::SmallVector<const Expr *, 8> LHSExprs;
1034 llvm::SmallVector<const Expr *, 8> RHSExprs;
1035 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001036 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001037 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001038 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001039 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001040 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1041 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1042 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1043 }
1044 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001045 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1046 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1047 D.getDirectiveKind() == OMPD_simd;
1048 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001049 // Emit nowait reduction if nowait clause is present or directive is a
1050 // parallel directive (it always has implicit barrier).
1051 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001052 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001053 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001054 }
1055}
1056
Alexey Bataev61205072016-03-02 04:57:40 +00001057static void emitPostUpdateForReductionClause(
1058 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1059 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1060 if (!CGF.HaveInsertPoint())
1061 return;
1062 llvm::BasicBlock *DoneBB = nullptr;
1063 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1064 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1065 if (!DoneBB) {
1066 if (auto *Cond = CondGen(CGF)) {
1067 // If the first post-update expression is found, emit conditional
1068 // block if it was requested.
1069 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1070 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1071 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1072 CGF.EmitBlock(ThenBB);
1073 }
1074 }
1075 CGF.EmitIgnoredExpr(PostUpdate);
1076 }
1077 }
1078 if (DoneBB)
1079 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1080}
1081
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001082namespace {
1083/// Codegen lambda for appending distribute lower and upper bounds to outlined
1084/// parallel function. This is necessary for combined constructs such as
1085/// 'distribute parallel for'
1086typedef llvm::function_ref<void(CodeGenFunction &,
1087 const OMPExecutableDirective &,
1088 llvm::SmallVectorImpl<llvm::Value *> &)>
1089 CodeGenBoundParametersTy;
1090} // anonymous namespace
1091
1092static void emitCommonOMPParallelDirective(
1093 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1094 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1095 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001096 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1097 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1098 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001099 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001100 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001101 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1102 /*IgnoreResultAssign*/ true);
1103 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1104 CGF, NumThreads, NumThreadsClause->getLocStart());
1105 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001106 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001107 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001108 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1109 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1110 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001111 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001112 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1113 if (C->getNameModifier() == OMPD_unknown ||
1114 C->getNameModifier() == OMPD_parallel) {
1115 IfCond = C->getCondition();
1116 break;
1117 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001118 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001119
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001120 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001121 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001122 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1123 // lower and upper bounds with the pragma 'for' chunking mechanism.
1124 // The following lambda takes care of appending the lower and upper bound
1125 // parameters when necessary
1126 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001127 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001128 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001129 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001130}
1131
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001132static void emitEmptyBoundParameters(CodeGenFunction &,
1133 const OMPExecutableDirective &,
1134 llvm::SmallVectorImpl<llvm::Value *> &) {}
1135
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001136void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001137 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001138 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001139 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001140 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001141 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1142 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001143 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001144 // propagation master's thread values of threadprivate variables to local
1145 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001146 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1147 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1148 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001149 }
1150 CGF.EmitOMPPrivateClause(S, PrivateScope);
1151 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1152 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001153 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001154 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001155 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001156 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1157 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001158 emitPostUpdateForReductionClause(
1159 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001160}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001161
Alexey Bataev0f34da12015-07-02 04:17:07 +00001162void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1163 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001164 RunCleanupsScope BodyScope(*this);
1165 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001166 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001167 EmitIgnoredExpr(I);
1168 }
Alexander Musman3276a272015-03-21 10:12:56 +00001169 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001170 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001171 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001172 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001173 }
1174
Alexander Musmana5f070a2014-10-01 06:03:56 +00001175 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001176 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001177 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001178 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001179 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001180 // The end (updates/cleanups).
1181 EmitBlock(Continue.getBlock());
1182 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001183}
1184
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001185void CodeGenFunction::EmitOMPInnerLoop(
1186 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1187 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001188 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1189 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001190 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001191
1192 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001193 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001194 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001195 const SourceRange &R = S.getSourceRange();
1196 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1197 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001198
1199 // If there are any cleanups between here and the loop-exit scope,
1200 // create a block to stage a loop exit along.
1201 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001202 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001203 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001204
Alexander Musmand196ef22014-10-07 08:57:09 +00001205 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001206
Alexey Bataev2df54a02015-03-12 08:53:29 +00001207 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001208 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001209 if (ExitBlock != LoopExit.getBlock()) {
1210 EmitBlock(ExitBlock);
1211 EmitBranchThroughCleanup(LoopExit);
1212 }
1213
1214 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001215 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001216
1217 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001218 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001219 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1220
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001221 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001222
1223 // Emit "IV = IV + 1" and a back-edge to the condition block.
1224 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001225 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001226 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001227 BreakContinueStack.pop_back();
1228 EmitBranch(CondBlock);
1229 LoopStack.pop();
1230 // Emit the fall-through block.
1231 EmitBlock(LoopExit.getBlock());
1232}
1233
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001234void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001235 if (!HaveInsertPoint())
1236 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001237 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001238 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001239 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001240 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001241 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1242 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1243 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1244 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1245 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1246 VD->getInit()->getType(), VK_LValue,
1247 VD->getInit()->getExprLoc());
1248 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1249 VD->getType()),
1250 /*capturedByInit=*/false);
1251 EmitAutoVarCleanups(Emission);
1252 } else
1253 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001254 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001255 // Emit the linear steps for the linear clauses.
1256 // If a step is not constant, it is pre-calculated before the loop.
1257 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1258 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001259 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001260 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001261 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001262 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001263 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001264}
1265
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001266void CodeGenFunction::EmitOMPLinearClauseFinal(
1267 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001268 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001269 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001270 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001271 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001272 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001273 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001274 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001275 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001276 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001277 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001278 // If the first post-update expression is found, emit conditional
1279 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001280 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1281 DoneBB = createBasicBlock(".omp.linear.pu.done");
1282 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1283 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001284 }
1285 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001286 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1287 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001288 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001289 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001290 Address OrigAddr = EmitLValue(&DRE).getAddress();
1291 CodeGenFunction::OMPPrivateScope VarScope(*this);
1292 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001293 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001294 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001295 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001296 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001297 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001298 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001299 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001300 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001301 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001302}
1303
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001304static void emitAlignedClause(CodeGenFunction &CGF,
1305 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001306 if (!CGF.HaveInsertPoint())
1307 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001308 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001309 unsigned ClauseAlignment = 0;
1310 if (auto AlignmentExpr = Clause->getAlignment()) {
1311 auto AlignmentCI =
1312 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1313 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001314 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001315 for (auto E : Clause->varlists()) {
1316 unsigned Alignment = ClauseAlignment;
1317 if (Alignment == 0) {
1318 // OpenMP [2.8.1, Description]
1319 // If no optional parameter is specified, implementation-defined default
1320 // alignments for SIMD instructions on the target platforms are assumed.
1321 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001322 CGF.getContext()
1323 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1324 E->getType()->getPointeeType()))
1325 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001326 }
1327 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1328 "alignment is not power of 2");
1329 if (Alignment != 0) {
1330 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1331 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1332 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001333 }
1334 }
1335}
1336
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001337void CodeGenFunction::EmitOMPPrivateLoopCounters(
1338 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1339 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001340 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001341 auto I = S.private_counters().begin();
1342 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001343 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1344 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001345 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001346 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001347 if (!LocalDeclMap.count(PrivateVD)) {
1348 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1349 EmitAutoVarCleanups(VarEmission);
1350 }
1351 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1352 /*RefersToEnclosingVariableOrCapture=*/false,
1353 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1354 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001355 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001356 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1357 VD->hasGlobalStorage()) {
1358 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1359 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1360 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1361 E->getType(), VK_LValue, E->getExprLoc());
1362 return EmitLValue(&DRE).getAddress();
1363 });
1364 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001365 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001366 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001367}
1368
Alexey Bataev62dbb972015-04-22 11:59:37 +00001369static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1370 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1371 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001372 if (!CGF.HaveInsertPoint())
1373 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001374 {
1375 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001376 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001377 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001378 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001379 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001380 CGF.EmitIgnoredExpr(I);
1381 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001382 }
1383 // Check that loop is executed at least one time.
1384 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1385}
1386
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001387void CodeGenFunction::EmitOMPLinearClause(
1388 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1389 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001390 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001391 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1392 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1393 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1394 for (auto *C : LoopDirective->counters()) {
1395 SIMDLCVs.insert(
1396 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1397 }
1398 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001399 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001400 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001401 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001402 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1403 auto *PrivateVD =
1404 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001405 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1406 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1407 // Emit private VarDecl with copy init.
1408 EmitVarDecl(*PrivateVD);
1409 return GetAddrOfLocalVar(PrivateVD);
1410 });
1411 assert(IsRegistered && "linear var already registered as private");
1412 // Silence the warning about unused variable.
1413 (void)IsRegistered;
1414 } else
1415 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001416 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001417 }
1418 }
1419}
1420
Alexey Bataev45bfad52015-08-21 12:19:04 +00001421static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001422 const OMPExecutableDirective &D,
1423 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001424 if (!CGF.HaveInsertPoint())
1425 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001426 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001427 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1428 /*ignoreResult=*/true);
1429 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1430 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1431 // In presence of finite 'safelen', it may be unsafe to mark all
1432 // the memory instructions parallel, because loop-carried
1433 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001434 if (!IsMonotonic)
1435 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001436 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001437 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1438 /*ignoreResult=*/true);
1439 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001440 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001441 // In presence of finite 'safelen', it may be unsafe to mark all
1442 // the memory instructions parallel, because loop-carried
1443 // dependences of 'safelen' iterations are possible.
1444 CGF.LoopStack.setParallel(false);
1445 }
1446}
1447
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001448void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1449 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001450 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001451 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001452 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001453 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001454}
1455
Alexey Bataevef549a82016-03-09 09:49:09 +00001456void CodeGenFunction::EmitOMPSimdFinal(
1457 const OMPLoopDirective &D,
1458 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001459 if (!HaveInsertPoint())
1460 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001461 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001462 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001463 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001464 for (auto F : D.finals()) {
1465 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001466 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1467 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1468 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1469 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001470 if (!DoneBB) {
1471 if (auto *Cond = CondGen(*this)) {
1472 // If the first post-update expression is found, emit conditional
1473 // block if it was requested.
1474 auto *ThenBB = createBasicBlock(".omp.final.then");
1475 DoneBB = createBasicBlock(".omp.final.done");
1476 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1477 EmitBlock(ThenBB);
1478 }
1479 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001480 Address OrigAddr = Address::invalid();
1481 if (CED)
1482 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1483 else {
1484 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1485 /*RefersToEnclosingVariableOrCapture=*/false,
1486 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1487 OrigAddr = EmitLValue(&DRE).getAddress();
1488 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001489 OMPPrivateScope VarScope(*this);
1490 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001491 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001492 (void)VarScope.Privatize();
1493 EmitIgnoredExpr(F);
1494 }
1495 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001496 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001497 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001498 if (DoneBB)
1499 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001500}
1501
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001502static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1503 const OMPLoopDirective &S,
1504 CodeGenFunction::JumpDest LoopExit) {
1505 CGF.EmitOMPLoopBody(S, LoopExit);
1506 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001507}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001508
Alexander Musman515ad8c2014-05-22 08:54:05 +00001509void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001510 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001511 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001512 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001513 // for (IV in 0..LastIteration) BODY;
1514 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001515 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001516 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001517
Alexey Bataev62dbb972015-04-22 11:59:37 +00001518 // Emit: if (PreCond) - begin.
1519 // If the condition constant folds and can be elided, avoid emitting the
1520 // whole loop.
1521 bool CondConstant;
1522 llvm::BasicBlock *ContBlock = nullptr;
1523 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1524 if (!CondConstant)
1525 return;
1526 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001527 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1528 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001529 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1530 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001531 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001532 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001533 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001534
1535 // Emit the loop iteration variable.
1536 const Expr *IVExpr = S.getIterationVariable();
1537 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1538 CGF.EmitVarDecl(*IVDecl);
1539 CGF.EmitIgnoredExpr(S.getInit());
1540
1541 // Emit the iterations count variable.
1542 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001543 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001544 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1545 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1546 // Emit calculation of the iterations count.
1547 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001548 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001549
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001550 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001551
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001552 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001553 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001554 {
1555 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001556 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1557 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001558 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001559 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001560 bool HasLastprivateClause =
1561 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001562 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001563 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1564 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001565 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001566 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001567 CGF.EmitStopPoint(&S);
1568 },
1569 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001570 CGF.EmitOMPSimdFinal(
1571 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001572 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001573 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001574 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001575 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001576 emitPostUpdateForReductionClause(
1577 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001578 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001579 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001580 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001581 // Emit: if (PreCond) - end.
1582 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001583 CGF.EmitBranch(ContBlock);
1584 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001585 }
1586 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001587 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001588 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001589}
1590
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001591void CodeGenFunction::EmitOMPOuterLoop(
1592 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1593 CodeGenFunction::OMPPrivateScope &LoopScope,
1594 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1595 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1596 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001597 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001598
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001599 const Expr *IVExpr = S.getIterationVariable();
1600 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1601 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1602
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001603 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1604
1605 // Start the loop with a block that tests the condition.
1606 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1607 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001608 const SourceRange &R = S.getSourceRange();
1609 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1610 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001611
1612 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001613 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001614 // UB = min(UB, GlobalUB) or
1615 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1616 // 'distribute parallel for')
1617 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001618 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001619 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001620 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001621 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001622 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001623 BoolCondVal =
1624 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1625 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001626 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001627
1628 // If there are any cleanups between here and the loop-exit scope,
1629 // create a block to stage a loop exit along.
1630 auto ExitBlock = LoopExit.getBlock();
1631 if (LoopScope.requiresCleanups())
1632 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1633
1634 auto LoopBody = createBasicBlock("omp.dispatch.body");
1635 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1636 if (ExitBlock != LoopExit.getBlock()) {
1637 EmitBlock(ExitBlock);
1638 EmitBranchThroughCleanup(LoopExit);
1639 }
1640 EmitBlock(LoopBody);
1641
Alexander Musman92bdaab2015-03-12 13:37:50 +00001642 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1643 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001644 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001645 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001646
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001647 // Create a block for the increment.
1648 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1649 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1650
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001651 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1652 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001653 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1654 LoopStack.setParallel(!IsMonotonic);
1655 else
1656 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001657
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001658 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001659
1660 // when 'distribute' is not combined with a 'for':
1661 // while (idx <= UB) { BODY; ++idx; }
1662 // when 'distribute' is combined with a 'for'
1663 // (e.g. 'distribute parallel for')
1664 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1665 EmitOMPInnerLoop(
1666 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1667 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1668 CodeGenLoop(CGF, S, LoopExit);
1669 },
1670 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1671 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1672 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001673
1674 EmitBlock(Continue.getBlock());
1675 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001676 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001677 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001678 EmitIgnoredExpr(LoopArgs.NextLB);
1679 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001680 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001681
1682 EmitBranch(CondBlock);
1683 LoopStack.pop();
1684 // Emit the fall-through block.
1685 EmitBlock(LoopExit.getBlock());
1686
1687 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001688 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1689 if (!DynamicOrOrdered)
1690 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1691 };
1692 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001693}
1694
1695void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001696 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001697 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001698 const OMPLoopArguments &LoopArgs,
1699 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001700 auto &RT = CGM.getOpenMPRuntime();
1701
1702 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001703 const bool DynamicOrOrdered =
1704 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001705
1706 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001707 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001708 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001709 "static non-chunked schedule does not need outer loop");
1710
1711 // Emit outer loop.
1712 //
1713 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1714 // When schedule(dynamic,chunk_size) is specified, the iterations are
1715 // distributed to threads in the team in chunks as the threads request them.
1716 // Each thread executes a chunk of iterations, then requests another chunk,
1717 // until no chunks remain to be distributed. Each chunk contains chunk_size
1718 // iterations, except for the last chunk to be distributed, which may have
1719 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1720 //
1721 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1722 // to threads in the team in chunks as the executing threads request them.
1723 // Each thread executes a chunk of iterations, then requests another chunk,
1724 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1725 // each chunk is proportional to the number of unassigned iterations divided
1726 // by the number of threads in the team, decreasing to 1. For a chunk_size
1727 // with value k (greater than 1), the size of each chunk is determined in the
1728 // same way, with the restriction that the chunks do not contain fewer than k
1729 // iterations (except for the last chunk to be assigned, which may have fewer
1730 // than k iterations).
1731 //
1732 // When schedule(auto) is specified, the decision regarding scheduling is
1733 // delegated to the compiler and/or runtime system. The programmer gives the
1734 // implementation the freedom to choose any possible mapping of iterations to
1735 // threads in the team.
1736 //
1737 // When schedule(runtime) is specified, the decision regarding scheduling is
1738 // deferred until run time, and the schedule and chunk size are taken from the
1739 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1740 // implementation defined
1741 //
1742 // while(__kmpc_dispatch_next(&LB, &UB)) {
1743 // idx = LB;
1744 // while (idx <= UB) { BODY; ++idx;
1745 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1746 // } // inner loop
1747 // }
1748 //
1749 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1750 // When schedule(static, chunk_size) is specified, iterations are divided into
1751 // chunks of size chunk_size, and the chunks are assigned to the threads in
1752 // the team in a round-robin fashion in the order of the thread number.
1753 //
1754 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1755 // while (idx <= UB) { BODY; ++idx; } // inner loop
1756 // LB = LB + ST;
1757 // UB = UB + ST;
1758 // }
1759 //
1760
1761 const Expr *IVExpr = S.getIterationVariable();
1762 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1763 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1764
1765 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001766 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1767 llvm::Value *LBVal = DispatchBounds.first;
1768 llvm::Value *UBVal = DispatchBounds.second;
1769 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1770 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001771 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001772 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001773 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001774 CGOpenMPRuntime::StaticRTInput StaticInit(
1775 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1776 LoopArgs.ST, LoopArgs.Chunk);
1777 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1778 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001779 }
1780
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001781 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1782 const unsigned IVSize,
1783 const bool IVSigned) {
1784 if (Ordered) {
1785 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1786 IVSigned);
1787 }
1788 };
1789
1790 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1791 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1792 OuterLoopArgs.IncExpr = S.getInc();
1793 OuterLoopArgs.Init = S.getInit();
1794 OuterLoopArgs.Cond = S.getCond();
1795 OuterLoopArgs.NextLB = S.getNextLowerBound();
1796 OuterLoopArgs.NextUB = S.getNextUpperBound();
1797 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1798 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001799}
1800
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001801static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1802 const unsigned IVSize, const bool IVSigned) {}
1803
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001804void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001805 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1806 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1807 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001808
1809 auto &RT = CGM.getOpenMPRuntime();
1810
1811 // Emit outer loop.
1812 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1813 // dynamic
1814 //
1815
1816 const Expr *IVExpr = S.getIterationVariable();
1817 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1818 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1819
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001820 CGOpenMPRuntime::StaticRTInput StaticInit(
1821 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1822 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1823 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001824
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001825 // for combined 'distribute' and 'for' the increment expression of distribute
1826 // is store in DistInc. For 'distribute' alone, it is in Inc.
1827 Expr *IncExpr;
1828 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1829 IncExpr = S.getDistInc();
1830 else
1831 IncExpr = S.getInc();
1832
1833 // this routine is shared by 'omp distribute parallel for' and
1834 // 'omp distribute': select the right EUB expression depending on the
1835 // directive
1836 OMPLoopArguments OuterLoopArgs;
1837 OuterLoopArgs.LB = LoopArgs.LB;
1838 OuterLoopArgs.UB = LoopArgs.UB;
1839 OuterLoopArgs.ST = LoopArgs.ST;
1840 OuterLoopArgs.IL = LoopArgs.IL;
1841 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1842 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1843 ? S.getCombinedEnsureUpperBound()
1844 : S.getEnsureUpperBound();
1845 OuterLoopArgs.IncExpr = IncExpr;
1846 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1847 ? S.getCombinedInit()
1848 : S.getInit();
1849 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1850 ? S.getCombinedCond()
1851 : S.getCond();
1852 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1853 ? S.getCombinedNextLowerBound()
1854 : S.getNextLowerBound();
1855 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1856 ? S.getCombinedNextUpperBound()
1857 : S.getNextUpperBound();
1858
1859 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1860 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1861 emitEmptyOrdered);
1862}
1863
1864/// Emit a helper variable and return corresponding lvalue.
1865static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1866 const DeclRefExpr *Helper) {
1867 auto VDecl = cast<VarDecl>(Helper->getDecl());
1868 CGF.EmitVarDecl(*VDecl);
1869 return CGF.EmitLValue(Helper);
1870}
1871
1872static std::pair<LValue, LValue>
1873emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1874 const OMPExecutableDirective &S) {
1875 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1876 LValue LB =
1877 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1878 LValue UB =
1879 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1880
1881 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1882 // parallel for') we need to use the 'distribute'
1883 // chunk lower and upper bounds rather than the whole loop iteration
1884 // space. These are parameters to the outlined function for 'parallel'
1885 // and we copy the bounds of the previous schedule into the
1886 // the current ones.
1887 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1888 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1889 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1890 PrevLBVal = CGF.EmitScalarConversion(
1891 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1892 LS.getIterationVariable()->getType(), SourceLocation());
1893 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1894 PrevUBVal = CGF.EmitScalarConversion(
1895 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1896 LS.getIterationVariable()->getType(), SourceLocation());
1897
1898 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1899 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1900
1901 return {LB, UB};
1902}
1903
1904/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1905/// we need to use the LB and UB expressions generated by the worksharing
1906/// code generation support, whereas in non combined situations we would
1907/// just emit 0 and the LastIteration expression
1908/// This function is necessary due to the difference of the LB and UB
1909/// types for the RT emission routines for 'for_static_init' and
1910/// 'for_dispatch_init'
1911static std::pair<llvm::Value *, llvm::Value *>
1912emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1913 const OMPExecutableDirective &S,
1914 Address LB, Address UB) {
1915 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1916 const Expr *IVExpr = LS.getIterationVariable();
1917 // when implementing a dynamic schedule for a 'for' combined with a
1918 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1919 // is not normalized as each team only executes its own assigned
1920 // distribute chunk
1921 QualType IteratorTy = IVExpr->getType();
1922 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1923 SourceLocation());
1924 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1925 SourceLocation());
1926 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001927}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001928
1929static void emitDistributeParallelForDistributeInnerBoundParams(
1930 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1931 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1932 const auto &Dir = cast<OMPLoopDirective>(S);
1933 LValue LB =
1934 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1935 auto LBCast = CGF.Builder.CreateIntCast(
1936 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1937 CapturedVars.push_back(LBCast);
1938 LValue UB =
1939 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1940
1941 auto UBCast = CGF.Builder.CreateIntCast(
1942 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1943 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00001944}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001945
1946static void
1947emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
1948 const OMPLoopDirective &S,
1949 CodeGenFunction::JumpDest LoopExit) {
1950 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
1951 PrePostActionTy &) {
1952 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
1953 emitDistributeParallelForInnerBounds,
1954 emitDistributeParallelForDispatchBounds);
1955 };
1956
1957 emitCommonOMPParallelDirective(
1958 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
1959 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001960}
1961
Carlo Bertolli9925f152016-06-27 14:55:37 +00001962void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1963 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001964 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1965 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
1966 S.getDistInc());
1967 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00001968 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001969 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
1970 /*HasCancel=*/false);
1971 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
1972 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001973}
1974
Kelvin Li4a39add2016-07-05 05:00:15 +00001975void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1976 const OMPDistributeParallelForSimdDirective &S) {
1977 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1978 CGM.getOpenMPRuntime().emitInlinedDirective(
1979 *this, OMPD_distribute_parallel_for_simd,
1980 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1981 OMPLoopScope PreInitScope(CGF, S);
1982 CGF.EmitStmt(
1983 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1984 });
1985}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001986
1987void CodeGenFunction::EmitOMPDistributeSimdDirective(
1988 const OMPDistributeSimdDirective &S) {
1989 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1990 CGM.getOpenMPRuntime().emitInlinedDirective(
1991 *this, OMPD_distribute_simd,
1992 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1993 OMPLoopScope PreInitScope(CGF, S);
1994 CGF.EmitStmt(
1995 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1996 });
1997}
1998
Kelvin Lia579b912016-07-14 02:54:56 +00001999void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
2000 const OMPTargetParallelForSimdDirective &S) {
2001 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2002 CGM.getOpenMPRuntime().emitInlinedDirective(
2003 *this, OMPD_target_parallel_for_simd,
2004 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2005 OMPLoopScope PreInitScope(CGF, S);
2006 CGF.EmitStmt(
2007 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2008 });
2009}
2010
Kelvin Li986330c2016-07-20 22:57:10 +00002011void CodeGenFunction::EmitOMPTargetSimdDirective(
2012 const OMPTargetSimdDirective &S) {
2013 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2014 CGM.getOpenMPRuntime().emitInlinedDirective(
2015 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2016 OMPLoopScope PreInitScope(CGF, S);
2017 CGF.EmitStmt(
2018 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2019 });
2020}
2021
Kelvin Li02532872016-08-05 14:37:37 +00002022void CodeGenFunction::EmitOMPTeamsDistributeDirective(
2023 const OMPTeamsDistributeDirective &S) {
2024 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2025 CGM.getOpenMPRuntime().emitInlinedDirective(
2026 *this, OMPD_teams_distribute,
2027 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2028 OMPLoopScope PreInitScope(CGF, S);
2029 CGF.EmitStmt(
2030 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2031 });
2032}
2033
Kelvin Li4e325f72016-10-25 12:50:55 +00002034void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2035 const OMPTeamsDistributeSimdDirective &S) {
2036 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2037 CGM.getOpenMPRuntime().emitInlinedDirective(
2038 *this, OMPD_teams_distribute_simd,
2039 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2040 OMPLoopScope PreInitScope(CGF, S);
2041 CGF.EmitStmt(
2042 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2043 });
2044}
2045
Kelvin Li579e41c2016-11-30 23:51:03 +00002046void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2047 const OMPTeamsDistributeParallelForSimdDirective &S) {
2048 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2049 CGM.getOpenMPRuntime().emitInlinedDirective(
2050 *this, OMPD_teams_distribute_parallel_for_simd,
2051 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2052 OMPLoopScope PreInitScope(CGF, S);
2053 CGF.EmitStmt(
2054 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2055 });
2056}
Kelvin Li4e325f72016-10-25 12:50:55 +00002057
Kelvin Li7ade93f2016-12-09 03:24:30 +00002058void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2059 const OMPTeamsDistributeParallelForDirective &S) {
2060 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2061 CGM.getOpenMPRuntime().emitInlinedDirective(
2062 *this, OMPD_teams_distribute_parallel_for,
2063 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2064 OMPLoopScope PreInitScope(CGF, S);
2065 CGF.EmitStmt(
2066 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2067 });
2068}
2069
Kelvin Li83c451e2016-12-25 04:52:54 +00002070void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2071 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002072 CGM.getOpenMPRuntime().emitInlinedDirective(
2073 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002074 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002075 CGF.EmitStmt(
2076 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002077 });
2078}
2079
Kelvin Li80e8f562016-12-29 22:16:30 +00002080void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2081 const OMPTargetTeamsDistributeParallelForDirective &S) {
2082 CGM.getOpenMPRuntime().emitInlinedDirective(
2083 *this, OMPD_target_teams_distribute_parallel_for,
2084 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2085 CGF.EmitStmt(
2086 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2087 });
2088}
2089
Kelvin Li1851df52017-01-03 05:23:48 +00002090void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2091 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2092 CGM.getOpenMPRuntime().emitInlinedDirective(
2093 *this, OMPD_target_teams_distribute_parallel_for_simd,
2094 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2095 CGF.EmitStmt(
2096 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2097 });
2098}
2099
Kelvin Lida681182017-01-10 18:08:18 +00002100void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2101 const OMPTargetTeamsDistributeSimdDirective &S) {
2102 CGM.getOpenMPRuntime().emitInlinedDirective(
2103 *this, OMPD_target_teams_distribute_simd,
2104 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2105 CGF.EmitStmt(
2106 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2107 });
2108}
2109
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002110namespace {
2111 struct ScheduleKindModifiersTy {
2112 OpenMPScheduleClauseKind Kind;
2113 OpenMPScheduleClauseModifier M1;
2114 OpenMPScheduleClauseModifier M2;
2115 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2116 OpenMPScheduleClauseModifier M1,
2117 OpenMPScheduleClauseModifier M2)
2118 : Kind(Kind), M1(M1), M2(M2) {}
2119 };
2120} // namespace
2121
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002122bool CodeGenFunction::EmitOMPWorksharingLoop(
2123 const OMPLoopDirective &S, Expr *EUB,
2124 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2125 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002126 // Emit the loop iteration variable.
2127 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2128 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2129 EmitVarDecl(*IVDecl);
2130
2131 // Emit the iterations count variable.
2132 // If it is not a variable, Sema decided to calculate iterations count on each
2133 // iteration (e.g., it is foldable into a constant).
2134 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2135 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2136 // Emit calculation of the iterations count.
2137 EmitIgnoredExpr(S.getCalcLastIteration());
2138 }
2139
2140 auto &RT = CGM.getOpenMPRuntime();
2141
Alexey Bataev38e89532015-04-16 04:54:05 +00002142 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002143 // Check pre-condition.
2144 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002145 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002146 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002147 // If the condition constant folds and can be elided, avoid emitting the
2148 // whole loop.
2149 bool CondConstant;
2150 llvm::BasicBlock *ContBlock = nullptr;
2151 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2152 if (!CondConstant)
2153 return false;
2154 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002155 auto *ThenBlock = createBasicBlock("omp.precond.then");
2156 ContBlock = createBasicBlock("omp.precond.end");
2157 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002158 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002159 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002160 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002161 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002162
Alexey Bataev8b427062016-05-25 12:36:08 +00002163 bool Ordered = false;
2164 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2165 if (OrderedClause->getNumForLoops())
2166 RT.emitDoacrossInit(*this, S);
2167 else
2168 Ordered = true;
2169 }
2170
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002171 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002172 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002173 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002174 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002175
2176 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2177 LValue LB = Bounds.first;
2178 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002179 LValue ST =
2180 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2181 LValue IL =
2182 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2183
Alexander Musmanc6388682014-12-15 07:07:06 +00002184 // Emit 'then' code.
2185 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002186 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002187 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2188 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002189 // initialization of firstprivate variables and post-update of
2190 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002191 CGM.getOpenMPRuntime().emitBarrierCall(
2192 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2193 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002194 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002195 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002196 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002197 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002198 EmitOMPPrivateLoopCounters(S, LoopScope);
2199 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002200 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002201
2202 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002203 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002204 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002205 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002206 ScheduleKind.Schedule = C->getScheduleKind();
2207 ScheduleKind.M1 = C->getFirstScheduleModifier();
2208 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002209 if (const auto *Ch = C->getChunkSize()) {
2210 Chunk = EmitScalarExpr(Ch);
2211 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2212 S.getIterationVariable()->getType(),
2213 S.getLocStart());
2214 }
2215 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002216 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2217 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002218 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2219 // If the static schedule kind is specified or if the ordered clause is
2220 // specified, and if no monotonic modifier is specified, the effect will
2221 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002222 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002223 /* Chunked */ Chunk != nullptr) &&
2224 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002225 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2226 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002227 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2228 // When no chunk_size is specified, the iteration space is divided into
2229 // chunks that are approximately equal in size, and at most one chunk is
2230 // distributed to each thread. Note that the size of the chunks is
2231 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002232 CGOpenMPRuntime::StaticRTInput StaticInit(
2233 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2234 UB.getAddress(), ST.getAddress());
2235 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2236 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002237 auto LoopExit =
2238 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002239 // UB = min(UB, GlobalUB);
2240 EmitIgnoredExpr(S.getEnsureUpperBound());
2241 // IV = LB;
2242 EmitIgnoredExpr(S.getInit());
2243 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002244 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2245 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002246 [&S, LoopExit](CodeGenFunction &CGF) {
2247 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002248 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002249 },
2250 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002251 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002252 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002253 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2254 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2255 };
2256 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002257 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002258 const bool IsMonotonic =
2259 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2260 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2261 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2262 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002263 // Emit the outer loop, which requests its work chunk [LB..UB] from
2264 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002265 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2266 ST.getAddress(), IL.getAddress(),
2267 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002268 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002269 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002270 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002271 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2272 EmitOMPSimdFinal(S,
2273 [&](CodeGenFunction &CGF) -> llvm::Value * {
2274 return CGF.Builder.CreateIsNotNull(
2275 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2276 });
2277 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002278 EmitOMPReductionClauseFinal(
2279 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2280 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2281 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002282 // Emit post-update of the reduction variables if IsLastIter != 0.
2283 emitPostUpdateForReductionClause(
2284 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2285 return CGF.Builder.CreateIsNotNull(
2286 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2287 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002288 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2289 if (HasLastprivateClause)
2290 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002291 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2292 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002293 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002294 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002295 return CGF.Builder.CreateIsNotNull(
2296 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2297 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002298 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002299 if (ContBlock) {
2300 EmitBranch(ContBlock);
2301 EmitBlock(ContBlock, true);
2302 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002303 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002304 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002305}
2306
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002307/// The following two functions generate expressions for the loop lower
2308/// and upper bounds in case of static and dynamic (dispatch) schedule
2309/// of the associated 'for' or 'distribute' loop.
2310static std::pair<LValue, LValue>
2311emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2312 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2313 LValue LB =
2314 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2315 LValue UB =
2316 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2317 return {LB, UB};
2318}
2319
2320/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2321/// consider the lower and upper bound expressions generated by the
2322/// worksharing loop support, but we use 0 and the iteration space size as
2323/// constants
2324static std::pair<llvm::Value *, llvm::Value *>
2325emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2326 Address LB, Address UB) {
2327 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2328 const Expr *IVExpr = LS.getIterationVariable();
2329 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2330 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2331 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2332 return {LBVal, UBVal};
2333}
2334
Alexander Musmanc6388682014-12-15 07:07:06 +00002335void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002336 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002337 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2338 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002339 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002340 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2341 emitForLoopBounds,
2342 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002343 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002344 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002345 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002346 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2347 S.hasCancel());
2348 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002349
2350 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002351 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002352 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2353 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002354}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002355
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002356void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002357 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002358 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2359 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002360 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2361 emitForLoopBounds,
2362 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002363 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002364 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002365 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002366 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2367 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002368
2369 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002370 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002371 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2372 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002373}
2374
Alexey Bataev2df54a02015-03-12 08:53:29 +00002375static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2376 const Twine &Name,
2377 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002378 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002379 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002380 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002381 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002382}
2383
Alexey Bataev3392d762016-02-16 11:18:12 +00002384void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002385 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2386 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002387 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002388 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2389 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002390 auto &C = CGF.CGM.getContext();
2391 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2392 // Emit helper vars inits.
2393 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2394 CGF.Builder.getInt32(0));
2395 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2396 : CGF.Builder.getInt32(0);
2397 LValue UB =
2398 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2399 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2400 CGF.Builder.getInt32(1));
2401 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2402 CGF.Builder.getInt32(0));
2403 // Loop counter.
2404 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2405 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2406 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2407 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2408 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2409 // Generate condition for loop.
2410 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002411 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002412 // Increment for loop counter.
2413 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2414 S.getLocStart());
2415 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2416 // Iterate through all sections and emit a switch construct:
2417 // switch (IV) {
2418 // case 0:
2419 // <SectionStmt[0]>;
2420 // break;
2421 // ...
2422 // case <NumSection> - 1:
2423 // <SectionStmt[<NumSection> - 1]>;
2424 // break;
2425 // }
2426 // .omp.sections.exit:
2427 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2428 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2429 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2430 CS == nullptr ? 1 : CS->size());
2431 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002432 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002433 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002434 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2435 CGF.EmitBlock(CaseBB);
2436 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002437 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002438 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002439 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002440 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002441 } else {
2442 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2443 CGF.EmitBlock(CaseBB);
2444 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2445 CGF.EmitStmt(Stmt);
2446 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002447 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002448 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002449 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002450
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002451 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2452 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002453 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002454 // initialization of firstprivate variables and post-update of lastprivate
2455 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002456 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2457 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2458 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002459 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002460 CGF.EmitOMPPrivateClause(S, LoopScope);
2461 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2462 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2463 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002464
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002465 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002466 OpenMPScheduleTy ScheduleKind;
2467 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002468 CGOpenMPRuntime::StaticRTInput StaticInit(
2469 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2470 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002471 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002472 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002473 // UB = min(UB, GlobalUB);
2474 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2475 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2476 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2477 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2478 // IV = LB;
2479 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2480 // while (idx <= UB) { BODY; ++idx; }
2481 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2482 [](CodeGenFunction &) {});
2483 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002484 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2485 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2486 };
2487 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002488 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002489 // Emit post-update of the reduction variables if IsLastIter != 0.
2490 emitPostUpdateForReductionClause(
2491 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2492 return CGF.Builder.CreateIsNotNull(
2493 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2494 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002495
2496 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2497 if (HasLastprivates)
2498 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002499 S, /*NoFinals=*/false,
2500 CGF.Builder.CreateIsNotNull(
2501 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002502 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002503
2504 bool HasCancel = false;
2505 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2506 HasCancel = OSD->hasCancel();
2507 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2508 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002509 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002510 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2511 HasCancel);
2512 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2513 // clause. Otherwise the barrier will be generated by the codegen for the
2514 // directive.
2515 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002516 // Emit implicit barrier to synchronize threads and avoid data races on
2517 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002518 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2519 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002520 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002521}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002522
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002523void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002524 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002525 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002526 EmitSections(S);
2527 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002528 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002529 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002530 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2531 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002532 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002533}
2534
2535void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002536 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002537 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002538 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002539 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002540 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2541 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002542}
2543
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002544void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002545 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002546 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002547 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002548 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002549 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002550 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002551 // Build a list of copyprivate variables along with helper expressions
2552 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002553 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002554 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002555 DestExprs.append(C->destination_exprs().begin(),
2556 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002557 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002558 AssignmentOps.append(C->assignment_ops().begin(),
2559 C->assignment_ops().end());
2560 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002561 // Emit code for 'single' region along with 'copyprivate' clauses
2562 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2563 Action.Enter(CGF);
2564 OMPPrivateScope SingleScope(CGF);
2565 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2566 CGF.EmitOMPPrivateClause(S, SingleScope);
2567 (void)SingleScope.Privatize();
2568 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2569 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002570 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002571 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002572 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2573 CopyprivateVars, DestExprs,
2574 SrcExprs, AssignmentOps);
2575 }
2576 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2577 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002578 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002579 CGM.getOpenMPRuntime().emitBarrierCall(
2580 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002581 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002582 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002583}
2584
Alexey Bataev8d690652014-12-04 07:23:53 +00002585void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002586 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2587 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002588 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002589 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002590 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002591 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002592}
2593
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002594void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002595 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2596 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002597 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002598 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002599 Expr *Hint = nullptr;
2600 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2601 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002602 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002603 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2604 S.getDirectiveName().getAsString(),
2605 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002606}
2607
Alexey Bataev671605e2015-04-13 05:28:11 +00002608void CodeGenFunction::EmitOMPParallelForDirective(
2609 const OMPParallelForDirective &S) {
2610 // Emit directive as a combined directive that consists of two implicit
2611 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002612 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002613 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002614 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2615 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002616 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002617 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2618 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002619}
2620
Alexander Musmane4e893b2014-09-23 09:33:00 +00002621void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002622 const OMPParallelForSimdDirective &S) {
2623 // Emit directive as a combined directive that consists of two implicit
2624 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002625 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002626 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2627 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002628 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002629 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2630 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002631}
2632
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002633void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002634 const OMPParallelSectionsDirective &S) {
2635 // Emit directive as a combined directive that consists of two implicit
2636 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002637 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2638 CGF.EmitSections(S);
2639 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002640 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2641 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002642}
2643
Alexey Bataev7292c292016-04-25 12:22:29 +00002644void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2645 const RegionCodeGenTy &BodyGen,
2646 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002647 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002648 // Emit outlined function for task construct.
2649 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002650 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002651 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002652 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002653 // Check if the task is final
2654 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2655 // If the condition constant folds and can be elided, try to avoid emitting
2656 // the condition and the dead arm of the if/else.
2657 auto *Cond = Clause->getCondition();
2658 bool CondConstant;
2659 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2660 Data.Final.setInt(CondConstant);
2661 else
2662 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2663 } else {
2664 // By default the task is not final.
2665 Data.Final.setInt(/*IntVal=*/false);
2666 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002667 // Check if the task has 'priority' clause.
2668 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002669 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002670 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002671 Data.Priority.setPointer(EmitScalarConversion(
2672 EmitScalarExpr(Prio), Prio->getType(),
2673 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2674 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002675 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002676 // The first function argument for tasks is a thread id, the second one is a
2677 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002678 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2679 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002680 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002681 auto IRef = C->varlist_begin();
2682 for (auto *IInit : C->private_copies()) {
2683 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2684 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002685 Data.PrivateVars.push_back(*IRef);
2686 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002687 }
2688 ++IRef;
2689 }
2690 }
2691 EmittedAsPrivate.clear();
2692 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002693 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002694 auto IRef = C->varlist_begin();
2695 auto IElemInitRef = C->inits().begin();
2696 for (auto *IInit : C->private_copies()) {
2697 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2698 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002699 Data.FirstprivateVars.push_back(*IRef);
2700 Data.FirstprivateCopies.push_back(IInit);
2701 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002702 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002703 ++IRef;
2704 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002705 }
2706 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002707 // Get list of lastprivate variables (for taskloops).
2708 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2709 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2710 auto IRef = C->varlist_begin();
2711 auto ID = C->destination_exprs().begin();
2712 for (auto *IInit : C->private_copies()) {
2713 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2714 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2715 Data.LastprivateVars.push_back(*IRef);
2716 Data.LastprivateCopies.push_back(IInit);
2717 }
2718 LastprivateDstsOrigs.insert(
2719 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2720 cast<DeclRefExpr>(*IRef)});
2721 ++IRef;
2722 ++ID;
2723 }
2724 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002725 SmallVector<const Expr *, 4> LHSs;
2726 SmallVector<const Expr *, 4> RHSs;
2727 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2728 auto IPriv = C->privates().begin();
2729 auto IRed = C->reduction_ops().begin();
2730 auto ILHS = C->lhs_exprs().begin();
2731 auto IRHS = C->rhs_exprs().begin();
2732 for (const auto *Ref : C->varlists()) {
2733 Data.ReductionVars.emplace_back(Ref);
2734 Data.ReductionCopies.emplace_back(*IPriv);
2735 Data.ReductionOps.emplace_back(*IRed);
2736 LHSs.emplace_back(*ILHS);
2737 RHSs.emplace_back(*IRHS);
2738 std::advance(IPriv, 1);
2739 std::advance(IRed, 1);
2740 std::advance(ILHS, 1);
2741 std::advance(IRHS, 1);
2742 }
2743 }
2744 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2745 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002746 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002747 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2748 for (auto *IRef : C->varlists())
2749 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002750 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002751 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002752 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002753 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002754 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2755 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002756 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002757 auto *CopyFn = CGF.Builder.CreateLoad(
2758 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2759 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2760 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2761 // Map privates.
2762 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2763 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2764 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002765 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002766 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2767 Address PrivatePtr = CGF.CreateMemTemp(
2768 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2769 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2770 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002771 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002772 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002773 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2774 Address PrivatePtr =
2775 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2776 ".firstpriv.ptr.addr");
2777 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2778 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002779 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002780 for (auto *E : Data.LastprivateVars) {
2781 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2782 Address PrivatePtr =
2783 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2784 ".lastpriv.ptr.addr");
2785 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2786 CallArgs.push_back(PrivatePtr.getPointer());
2787 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002788 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2789 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002790 for (auto &&Pair : LastprivateDstsOrigs) {
2791 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2792 DeclRefExpr DRE(
2793 const_cast<VarDecl *>(OrigVD),
2794 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2795 OrigVD) != nullptr,
2796 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2797 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2798 return CGF.EmitLValue(&DRE).getAddress();
2799 });
2800 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002801 for (auto &&Pair : PrivatePtrs) {
2802 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2803 CGF.getContext().getDeclAlign(Pair.first));
2804 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2805 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002806 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002807 if (Data.Reductions) {
2808 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2809 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2810 Data.ReductionOps);
2811 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2812 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2813 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2814 RedCG.emitSharedLValue(CGF, Cnt);
2815 RedCG.emitAggregateType(CGF, Cnt);
2816 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2817 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2818 Replacement =
2819 Address(CGF.EmitScalarConversion(
2820 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2821 CGF.getContext().getPointerType(
2822 Data.ReductionCopies[Cnt]->getType()),
2823 SourceLocation()),
2824 Replacement.getAlignment());
2825 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2826 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2827 [Replacement]() { return Replacement; });
2828 // FIXME: This must removed once the runtime library is fixed.
2829 // Emit required threadprivate variables for
2830 // initilizer/combiner/finalizer.
2831 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2832 RedCG, Cnt);
2833 }
2834 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002835 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002836 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002837 SmallVector<const Expr *, 4> InRedVars;
2838 SmallVector<const Expr *, 4> InRedPrivs;
2839 SmallVector<const Expr *, 4> InRedOps;
2840 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2841 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2842 auto IPriv = C->privates().begin();
2843 auto IRed = C->reduction_ops().begin();
2844 auto ITD = C->taskgroup_descriptors().begin();
2845 for (const auto *Ref : C->varlists()) {
2846 InRedVars.emplace_back(Ref);
2847 InRedPrivs.emplace_back(*IPriv);
2848 InRedOps.emplace_back(*IRed);
2849 TaskgroupDescriptors.emplace_back(*ITD);
2850 std::advance(IPriv, 1);
2851 std::advance(IRed, 1);
2852 std::advance(ITD, 1);
2853 }
2854 }
2855 // Privatize in_reduction items here, because taskgroup descriptors must be
2856 // privatized earlier.
2857 OMPPrivateScope InRedScope(CGF);
2858 if (!InRedVars.empty()) {
2859 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2860 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2861 RedCG.emitSharedLValue(CGF, Cnt);
2862 RedCG.emitAggregateType(CGF, Cnt);
2863 // The taskgroup descriptor variable is always implicit firstprivate and
2864 // privatized already during procoessing of the firstprivates.
2865 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2866 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2867 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2868 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2869 Replacement = Address(
2870 CGF.EmitScalarConversion(
2871 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2872 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2873 SourceLocation()),
2874 Replacement.getAlignment());
2875 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2876 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2877 [Replacement]() { return Replacement; });
2878 // FIXME: This must removed once the runtime library is fixed.
2879 // Emit required threadprivate variables for
2880 // initilizer/combiner/finalizer.
2881 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2882 RedCG, Cnt);
2883 }
2884 }
2885 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002886
2887 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002888 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002889 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002890 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2891 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2892 Data.NumberOfParts);
2893 OMPLexicalScope Scope(*this, S);
2894 TaskGen(*this, OutlinedFn, Data);
2895}
2896
2897void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2898 // Emit outlined function for task construct.
2899 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2900 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002901 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002902 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002903 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2904 if (C->getNameModifier() == OMPD_unknown ||
2905 C->getNameModifier() == OMPD_task) {
2906 IfCond = C->getCondition();
2907 break;
2908 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002909 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002910
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002911 OMPTaskDataTy Data;
2912 // Check if we should emit tied or untied task.
2913 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002914 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2915 CGF.EmitStmt(CS->getCapturedStmt());
2916 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002917 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002918 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002919 const OMPTaskDataTy &Data) {
2920 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2921 SharedsTy, CapturedStruct, IfCond,
2922 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002923 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002924 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002925}
2926
Alexey Bataev9f797f32015-02-05 05:57:51 +00002927void CodeGenFunction::EmitOMPTaskyieldDirective(
2928 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002929 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002930}
2931
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002932void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002933 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002934}
2935
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002936void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2937 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002938}
2939
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002940void CodeGenFunction::EmitOMPTaskgroupDirective(
2941 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002942 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2943 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002944 if (const Expr *E = S.getReductionRef()) {
2945 SmallVector<const Expr *, 4> LHSs;
2946 SmallVector<const Expr *, 4> RHSs;
2947 OMPTaskDataTy Data;
2948 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2949 auto IPriv = C->privates().begin();
2950 auto IRed = C->reduction_ops().begin();
2951 auto ILHS = C->lhs_exprs().begin();
2952 auto IRHS = C->rhs_exprs().begin();
2953 for (const auto *Ref : C->varlists()) {
2954 Data.ReductionVars.emplace_back(Ref);
2955 Data.ReductionCopies.emplace_back(*IPriv);
2956 Data.ReductionOps.emplace_back(*IRed);
2957 LHSs.emplace_back(*ILHS);
2958 RHSs.emplace_back(*IRHS);
2959 std::advance(IPriv, 1);
2960 std::advance(IRed, 1);
2961 std::advance(ILHS, 1);
2962 std::advance(IRHS, 1);
2963 }
2964 }
2965 llvm::Value *ReductionDesc =
2966 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2967 LHSs, RHSs, Data);
2968 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2969 CGF.EmitVarDecl(*VD);
2970 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2971 /*Volatile=*/false, E->getType());
2972 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002973 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002974 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002975 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002976 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2977}
2978
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002979void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002980 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002981 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002982 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2983 FlushClause->varlist_end());
2984 }
2985 return llvm::None;
2986 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002987}
2988
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002989void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
2990 const CodeGenLoopTy &CodeGenLoop,
2991 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002992 // Emit the loop iteration variable.
2993 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2994 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2995 EmitVarDecl(*IVDecl);
2996
2997 // Emit the iterations count variable.
2998 // If it is not a variable, Sema decided to calculate iterations count on each
2999 // iteration (e.g., it is foldable into a constant).
3000 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3001 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3002 // Emit calculation of the iterations count.
3003 EmitIgnoredExpr(S.getCalcLastIteration());
3004 }
3005
3006 auto &RT = CGM.getOpenMPRuntime();
3007
Carlo Bertolli962bb802017-01-03 18:24:42 +00003008 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003009 // Check pre-condition.
3010 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003011 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003012 // Skip the entire loop if we don't meet the precondition.
3013 // If the condition constant folds and can be elided, avoid emitting the
3014 // whole loop.
3015 bool CondConstant;
3016 llvm::BasicBlock *ContBlock = nullptr;
3017 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3018 if (!CondConstant)
3019 return;
3020 } else {
3021 auto *ThenBlock = createBasicBlock("omp.precond.then");
3022 ContBlock = createBasicBlock("omp.precond.end");
3023 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3024 getProfileCount(&S));
3025 EmitBlock(ThenBlock);
3026 incrementProfileCounter(&S);
3027 }
3028
3029 // Emit 'then' code.
3030 {
3031 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003032
3033 LValue LB = EmitOMPHelperVar(
3034 *this, cast<DeclRefExpr>(
3035 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3036 ? S.getCombinedLowerBoundVariable()
3037 : S.getLowerBoundVariable())));
3038 LValue UB = EmitOMPHelperVar(
3039 *this, cast<DeclRefExpr>(
3040 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3041 ? S.getCombinedUpperBoundVariable()
3042 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003043 LValue ST =
3044 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3045 LValue IL =
3046 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3047
3048 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003049 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3050 // Emit implicit barrier to synchronize threads and avoid data races on
3051 // initialization of firstprivate variables and post-update of
3052 // lastprivate variables.
3053 CGM.getOpenMPRuntime().emitBarrierCall(
3054 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3055 /*ForceSimpleCall=*/true);
3056 }
3057 EmitOMPPrivateClause(S, LoopScope);
3058 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003059 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003060 (void)LoopScope.Privatize();
3061
3062 // Detect the distribute schedule kind and chunk.
3063 llvm::Value *Chunk = nullptr;
3064 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3065 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3066 ScheduleKind = C->getDistScheduleKind();
3067 if (const auto *Ch = C->getChunkSize()) {
3068 Chunk = EmitScalarExpr(Ch);
3069 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3070 S.getIterationVariable()->getType(),
3071 S.getLocStart());
3072 }
3073 }
3074 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3075 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3076
3077 // OpenMP [2.10.8, distribute Construct, Description]
3078 // If dist_schedule is specified, kind must be static. If specified,
3079 // iterations are divided into chunks of size chunk_size, chunks are
3080 // assigned to the teams of the league in a round-robin fashion in the
3081 // order of the team number. When no chunk_size is specified, the
3082 // iteration space is divided into chunks that are approximately equal
3083 // in size, and at most one chunk is distributed to each team of the
3084 // league. The size of the chunks is unspecified in this case.
3085 if (RT.isStaticNonchunked(ScheduleKind,
3086 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003087 CGOpenMPRuntime::StaticRTInput StaticInit(
3088 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3089 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003090 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003091 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003092 auto LoopExit =
3093 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3094 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003095 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3096 ? S.getCombinedEnsureUpperBound()
3097 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003098 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003099 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3100 ? S.getCombinedInit()
3101 : S.getInit());
3102
3103 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3104 ? S.getCombinedCond()
3105 : S.getCond();
3106
3107 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003108 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003109 // when combined with 'for' (e.g. as in 'distribute parallel for')
3110 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3111 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3112 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3113 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003114 },
3115 [](CodeGenFunction &) {});
3116 EmitBlock(LoopExit.getBlock());
3117 // Tell the runtime we are done.
3118 RT.emitForStaticFinish(*this, S.getLocStart());
3119 } else {
3120 // Emit the outer loop, which requests its work chunk [LB..UB] from
3121 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003122 const OMPLoopArguments LoopArguments = {
3123 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3124 Chunk};
3125 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3126 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003127 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003128
3129 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3130 if (HasLastprivateClause)
3131 EmitOMPLastprivateClauseFinal(
3132 S, /*NoFinals=*/false,
3133 Builder.CreateIsNotNull(
3134 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003135 }
3136
3137 // We're now done with the loop, so jump to the continuation block.
3138 if (ContBlock) {
3139 EmitBranch(ContBlock);
3140 EmitBlock(ContBlock, true);
3141 }
3142 }
3143}
3144
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003145void CodeGenFunction::EmitOMPDistributeDirective(
3146 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003147 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003148
3149 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003150 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003151 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003152 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3153 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003154}
3155
Alexey Bataev5f600d62015-09-29 03:48:57 +00003156static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3157 const CapturedStmt *S) {
3158 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3159 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3160 CGF.CapturedStmtInfo = &CapStmtInfo;
3161 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3162 Fn->addFnAttr(llvm::Attribute::NoInline);
3163 return Fn;
3164}
3165
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003166void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003167 if (!S.getAssociatedStmt()) {
3168 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3169 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003170 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003171 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003172 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003173 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3174 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003175 if (C) {
3176 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3177 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3178 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3179 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003180 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3181 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003182 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003183 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003184 CGF.EmitStmt(
3185 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3186 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003187 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003188 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003189 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003190}
3191
Alexey Bataevb57056f2015-01-22 06:17:56 +00003192static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003193 QualType SrcType, QualType DestType,
3194 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003195 assert(CGF.hasScalarEvaluationKind(DestType) &&
3196 "DestType must have scalar evaluation kind.");
3197 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3198 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003199 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3200 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003201 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003202 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003203}
3204
3205static CodeGenFunction::ComplexPairTy
3206convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003207 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003208 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3209 "DestType must have complex evaluation kind.");
3210 CodeGenFunction::ComplexPairTy ComplexVal;
3211 if (Val.isScalar()) {
3212 // Convert the input element to the element type of the complex.
3213 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003214 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3215 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003216 ComplexVal = CodeGenFunction::ComplexPairTy(
3217 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3218 } else {
3219 assert(Val.isComplex() && "Must be a scalar or complex.");
3220 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3221 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3222 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003223 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003224 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003225 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003226 }
3227 return ComplexVal;
3228}
3229
Alexey Bataev5e018f92015-04-23 06:35:10 +00003230static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3231 LValue LVal, RValue RVal) {
3232 if (LVal.isGlobalReg()) {
3233 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3234 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003235 CGF.EmitAtomicStore(RVal, LVal,
3236 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3237 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003238 LVal.isVolatile(), /*IsInit=*/false);
3239 }
3240}
3241
Alexey Bataev8524d152016-01-21 12:35:58 +00003242void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3243 QualType RValTy, SourceLocation Loc) {
3244 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003245 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003246 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3247 *this, RVal, RValTy, LVal.getType(), Loc)),
3248 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003249 break;
3250 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003251 EmitStoreOfComplex(
3252 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003253 /*isInit=*/false);
3254 break;
3255 case TEK_Aggregate:
3256 llvm_unreachable("Must be a scalar or complex.");
3257 }
3258}
3259
Alexey Bataevb57056f2015-01-22 06:17:56 +00003260static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3261 const Expr *X, const Expr *V,
3262 SourceLocation Loc) {
3263 // v = x;
3264 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3265 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3266 LValue XLValue = CGF.EmitLValue(X);
3267 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003268 RValue Res = XLValue.isGlobalReg()
3269 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003270 : CGF.EmitAtomicLoad(
3271 XLValue, Loc,
3272 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3273 : llvm::AtomicOrdering::Monotonic,
3274 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003275 // OpenMP, 2.12.6, atomic Construct
3276 // Any atomic construct with a seq_cst clause forces the atomically
3277 // performed operation to include an implicit flush operation without a
3278 // list.
3279 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003280 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003281 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003282}
3283
Alexey Bataevb8329262015-02-27 06:33:30 +00003284static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3285 const Expr *X, const Expr *E,
3286 SourceLocation Loc) {
3287 // x = expr;
3288 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003289 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003290 // OpenMP, 2.12.6, atomic Construct
3291 // Any atomic construct with a seq_cst clause forces the atomically
3292 // performed operation to include an implicit flush operation without a
3293 // list.
3294 if (IsSeqCst)
3295 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3296}
3297
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003298static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3299 RValue Update,
3300 BinaryOperatorKind BO,
3301 llvm::AtomicOrdering AO,
3302 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003303 auto &Context = CGF.CGM.getContext();
3304 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003305 // expression is simple and atomic is allowed for the given type for the
3306 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003307 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003308 !Update.getScalarVal()->getType()->isIntegerTy() ||
3309 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3310 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003311 X.getAddress().getElementType())) ||
3312 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003313 !Context.getTargetInfo().hasBuiltinAtomic(
3314 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003315 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003316
3317 llvm::AtomicRMWInst::BinOp RMWOp;
3318 switch (BO) {
3319 case BO_Add:
3320 RMWOp = llvm::AtomicRMWInst::Add;
3321 break;
3322 case BO_Sub:
3323 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003324 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003325 RMWOp = llvm::AtomicRMWInst::Sub;
3326 break;
3327 case BO_And:
3328 RMWOp = llvm::AtomicRMWInst::And;
3329 break;
3330 case BO_Or:
3331 RMWOp = llvm::AtomicRMWInst::Or;
3332 break;
3333 case BO_Xor:
3334 RMWOp = llvm::AtomicRMWInst::Xor;
3335 break;
3336 case BO_LT:
3337 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3338 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3339 : llvm::AtomicRMWInst::Max)
3340 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3341 : llvm::AtomicRMWInst::UMax);
3342 break;
3343 case BO_GT:
3344 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3345 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3346 : llvm::AtomicRMWInst::Min)
3347 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3348 : llvm::AtomicRMWInst::UMin);
3349 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003350 case BO_Assign:
3351 RMWOp = llvm::AtomicRMWInst::Xchg;
3352 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003353 case BO_Mul:
3354 case BO_Div:
3355 case BO_Rem:
3356 case BO_Shl:
3357 case BO_Shr:
3358 case BO_LAnd:
3359 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003360 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003361 case BO_PtrMemD:
3362 case BO_PtrMemI:
3363 case BO_LE:
3364 case BO_GE:
3365 case BO_EQ:
3366 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003367 case BO_AddAssign:
3368 case BO_SubAssign:
3369 case BO_AndAssign:
3370 case BO_OrAssign:
3371 case BO_XorAssign:
3372 case BO_MulAssign:
3373 case BO_DivAssign:
3374 case BO_RemAssign:
3375 case BO_ShlAssign:
3376 case BO_ShrAssign:
3377 case BO_Comma:
3378 llvm_unreachable("Unsupported atomic update operation");
3379 }
3380 auto *UpdateVal = Update.getScalarVal();
3381 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3382 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003383 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003384 X.getType()->hasSignedIntegerRepresentation());
3385 }
John McCall7f416cc2015-09-08 08:05:57 +00003386 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003387 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003388}
3389
Alexey Bataev5e018f92015-04-23 06:35:10 +00003390std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003391 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3392 llvm::AtomicOrdering AO, SourceLocation Loc,
3393 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3394 // Update expressions are allowed to have the following forms:
3395 // x binop= expr; -> xrval + expr;
3396 // x++, ++x -> xrval + 1;
3397 // x--, --x -> xrval - 1;
3398 // x = x binop expr; -> xrval binop expr
3399 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003400 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3401 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003402 if (X.isGlobalReg()) {
3403 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3404 // 'xrval'.
3405 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3406 } else {
3407 // Perform compare-and-swap procedure.
3408 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003409 }
3410 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003411 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003412}
3413
3414static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3415 const Expr *X, const Expr *E,
3416 const Expr *UE, bool IsXLHSInRHSPart,
3417 SourceLocation Loc) {
3418 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3419 "Update expr in 'atomic update' must be a binary operator.");
3420 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3421 // Update expressions are allowed to have the following forms:
3422 // x binop= expr; -> xrval + expr;
3423 // x++, ++x -> xrval + 1;
3424 // x--, --x -> xrval - 1;
3425 // x = x binop expr; -> xrval binop expr
3426 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003427 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003428 LValue XLValue = CGF.EmitLValue(X);
3429 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003430 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3431 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003432 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3433 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3434 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3435 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3436 auto Gen =
3437 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3438 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3439 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3440 return CGF.EmitAnyExpr(UE);
3441 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003442 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3443 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3444 // OpenMP, 2.12.6, atomic Construct
3445 // Any atomic construct with a seq_cst clause forces the atomically
3446 // performed operation to include an implicit flush operation without a
3447 // list.
3448 if (IsSeqCst)
3449 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3450}
3451
3452static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003453 QualType SourceType, QualType ResType,
3454 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003455 switch (CGF.getEvaluationKind(ResType)) {
3456 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003457 return RValue::get(
3458 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003459 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003460 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003461 return RValue::getComplex(Res.first, Res.second);
3462 }
3463 case TEK_Aggregate:
3464 break;
3465 }
3466 llvm_unreachable("Must be a scalar or complex.");
3467}
3468
3469static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3470 bool IsPostfixUpdate, const Expr *V,
3471 const Expr *X, const Expr *E,
3472 const Expr *UE, bool IsXLHSInRHSPart,
3473 SourceLocation Loc) {
3474 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3475 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3476 RValue NewVVal;
3477 LValue VLValue = CGF.EmitLValue(V);
3478 LValue XLValue = CGF.EmitLValue(X);
3479 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003480 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3481 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003482 QualType NewVValType;
3483 if (UE) {
3484 // 'x' is updated with some additional value.
3485 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3486 "Update expr in 'atomic capture' must be a binary operator.");
3487 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3488 // Update expressions are allowed to have the following forms:
3489 // x binop= expr; -> xrval + expr;
3490 // x++, ++x -> xrval + 1;
3491 // x--, --x -> xrval - 1;
3492 // x = x binop expr; -> xrval binop expr
3493 // x = expr Op x; - > expr binop xrval;
3494 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3495 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3496 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3497 NewVValType = XRValExpr->getType();
3498 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3499 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003500 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003501 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3502 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3503 RValue Res = CGF.EmitAnyExpr(UE);
3504 NewVVal = IsPostfixUpdate ? XRValue : Res;
3505 return Res;
3506 };
3507 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3508 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3509 if (Res.first) {
3510 // 'atomicrmw' instruction was generated.
3511 if (IsPostfixUpdate) {
3512 // Use old value from 'atomicrmw'.
3513 NewVVal = Res.second;
3514 } else {
3515 // 'atomicrmw' does not provide new value, so evaluate it using old
3516 // value of 'x'.
3517 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3518 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3519 NewVVal = CGF.EmitAnyExpr(UE);
3520 }
3521 }
3522 } else {
3523 // 'x' is simply rewritten with some 'expr'.
3524 NewVValType = X->getType().getNonReferenceType();
3525 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003526 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003527 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003528 NewVVal = XRValue;
3529 return ExprRValue;
3530 };
3531 // Try to perform atomicrmw xchg, otherwise simple exchange.
3532 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3533 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3534 Loc, Gen);
3535 if (Res.first) {
3536 // 'atomicrmw' instruction was generated.
3537 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3538 }
3539 }
3540 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003541 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003542 // OpenMP, 2.12.6, atomic Construct
3543 // Any atomic construct with a seq_cst clause forces the atomically
3544 // performed operation to include an implicit flush operation without a
3545 // list.
3546 if (IsSeqCst)
3547 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3548}
3549
Alexey Bataevb57056f2015-01-22 06:17:56 +00003550static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003551 bool IsSeqCst, bool IsPostfixUpdate,
3552 const Expr *X, const Expr *V, const Expr *E,
3553 const Expr *UE, bool IsXLHSInRHSPart,
3554 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003555 switch (Kind) {
3556 case OMPC_read:
3557 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3558 break;
3559 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003560 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3561 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003562 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003563 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003564 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3565 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003566 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003567 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3568 IsXLHSInRHSPart, Loc);
3569 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003570 case OMPC_if:
3571 case OMPC_final:
3572 case OMPC_num_threads:
3573 case OMPC_private:
3574 case OMPC_firstprivate:
3575 case OMPC_lastprivate:
3576 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003577 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003578 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003579 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003580 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003581 case OMPC_collapse:
3582 case OMPC_default:
3583 case OMPC_seq_cst:
3584 case OMPC_shared:
3585 case OMPC_linear:
3586 case OMPC_aligned:
3587 case OMPC_copyin:
3588 case OMPC_copyprivate:
3589 case OMPC_flush:
3590 case OMPC_proc_bind:
3591 case OMPC_schedule:
3592 case OMPC_ordered:
3593 case OMPC_nowait:
3594 case OMPC_untied:
3595 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003596 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003597 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003598 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003599 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003600 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003601 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003602 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003603 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003604 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003605 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003606 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003607 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003608 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003609 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003610 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003611 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003612 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003613 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003614 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003615 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003616 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3617 }
3618}
3619
3620void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003621 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003622 OpenMPClauseKind Kind = OMPC_unknown;
3623 for (auto *C : S.clauses()) {
3624 // Find first clause (skip seq_cst clause, if it is first).
3625 if (C->getClauseKind() != OMPC_seq_cst) {
3626 Kind = C->getClauseKind();
3627 break;
3628 }
3629 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003630
3631 const auto *CS =
3632 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003633 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003634 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003635 }
3636 // Processing for statements under 'atomic capture'.
3637 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3638 for (const auto *C : Compound->body()) {
3639 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3640 enterFullExpression(EWC);
3641 }
3642 }
3643 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003644
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003645 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3646 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003647 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003648 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3649 S.getV(), S.getExpr(), S.getUpdateExpr(),
3650 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003651 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003652 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003653 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003654}
3655
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003656static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3657 const OMPExecutableDirective &S,
3658 const RegionCodeGenTy &CodeGen) {
3659 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3660 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003661 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3662
Samuel Antaoee8fb302016-01-06 13:42:12 +00003663 llvm::Function *Fn = nullptr;
3664 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003665
Samuel Antaobed3c462015-10-02 16:14:20 +00003666 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003667 // Check for the at most one if clause associated with the target region.
3668 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3669 if (C->getNameModifier() == OMPD_unknown ||
3670 C->getNameModifier() == OMPD_target) {
3671 IfCond = C->getCondition();
3672 break;
3673 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003674 }
3675
3676 // Check if we have any device clause associated with the directive.
3677 const Expr *Device = nullptr;
3678 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3679 Device = C->getDevice();
3680 }
3681
Samuel Antaoee8fb302016-01-06 13:42:12 +00003682 // Check if we have an if clause whose conditional always evaluates to false
3683 // or if we do not have any targets specified. If so the target region is not
3684 // an offload entry point.
3685 bool IsOffloadEntry = true;
3686 if (IfCond) {
3687 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003688 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003689 IsOffloadEntry = false;
3690 }
3691 if (CGM.getLangOpts().OMPTargetTriples.empty())
3692 IsOffloadEntry = false;
3693
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003694 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003695 StringRef ParentName;
3696 // In case we have Ctors/Dtors we use the complete type variant to produce
3697 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003698 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003699 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003700 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003701 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3702 else
3703 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003704 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003705
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003706 // Emit target region as a standalone region.
3707 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3708 IsOffloadEntry, CodeGen);
3709 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003710 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3711 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003712 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003713 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003714}
3715
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003716static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3717 PrePostActionTy &Action) {
3718 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3719 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3720 CGF.EmitOMPPrivateClause(S, PrivateScope);
3721 (void)PrivateScope.Privatize();
3722
3723 Action.Enter(CGF);
3724 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3725}
3726
3727void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3728 StringRef ParentName,
3729 const OMPTargetDirective &S) {
3730 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3731 emitTargetRegion(CGF, S, Action);
3732 };
3733 llvm::Function *Fn;
3734 llvm::Constant *Addr;
3735 // Emit target region as a standalone region.
3736 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3737 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3738 assert(Fn && Addr && "Target device function emission failed.");
3739}
3740
3741void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3742 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3743 emitTargetRegion(CGF, S, Action);
3744 };
3745 emitCommonOMPTargetDirective(*this, S, CodeGen);
3746}
3747
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003748static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3749 const OMPExecutableDirective &S,
3750 OpenMPDirectiveKind InnermostKind,
3751 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003752 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3753 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3754 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003755
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003756 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3757 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003758 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003759 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3760 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003761
Carlo Bertollic6872252016-04-04 15:55:02 +00003762 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3763 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003764 }
3765
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003766 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003767 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3768 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003769 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3770 CapturedVars);
3771}
3772
3773void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003774 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003775 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003776 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003777 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3778 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003779 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003780 (void)PrivateScope.Privatize();
3781 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003782 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003783 };
3784 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003785 emitPostUpdateForReductionClause(
3786 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003787}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003788
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003789static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3790 const OMPTargetTeamsDirective &S) {
3791 auto *CS = S.getCapturedStmt(OMPD_teams);
3792 Action.Enter(CGF);
3793 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3794 // TODO: Add support for clauses.
3795 CGF.EmitStmt(CS->getCapturedStmt());
3796 };
3797 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3798}
3799
3800void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3801 CodeGenModule &CGM, StringRef ParentName,
3802 const OMPTargetTeamsDirective &S) {
3803 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3804 emitTargetTeamsRegion(CGF, Action, S);
3805 };
3806 llvm::Function *Fn;
3807 llvm::Constant *Addr;
3808 // Emit target region as a standalone region.
3809 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3810 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3811 assert(Fn && Addr && "Target device function emission failed.");
3812}
3813
3814void CodeGenFunction::EmitOMPTargetTeamsDirective(
3815 const OMPTargetTeamsDirective &S) {
3816 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3817 emitTargetTeamsRegion(CGF, Action, S);
3818 };
3819 emitCommonOMPTargetDirective(*this, S, CodeGen);
3820}
3821
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003822void CodeGenFunction::EmitOMPCancellationPointDirective(
3823 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003824 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3825 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003826}
3827
Alexey Bataev80909872015-07-02 11:25:17 +00003828void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003829 const Expr *IfCond = nullptr;
3830 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3831 if (C->getNameModifier() == OMPD_unknown ||
3832 C->getNameModifier() == OMPD_cancel) {
3833 IfCond = C->getCondition();
3834 break;
3835 }
3836 }
3837 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003838 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003839}
3840
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003841CodeGenFunction::JumpDest
3842CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003843 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3844 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003845 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003846 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003847 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3848 Kind == OMPD_distribute_parallel_for ||
3849 Kind == OMPD_target_parallel_for);
3850 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003851}
Michael Wong65f367f2015-07-21 13:44:28 +00003852
Samuel Antaocc10b852016-07-28 14:23:26 +00003853void CodeGenFunction::EmitOMPUseDevicePtrClause(
3854 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3855 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3856 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3857 auto OrigVarIt = C.varlist_begin();
3858 auto InitIt = C.inits().begin();
3859 for (auto PvtVarIt : C.private_copies()) {
3860 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3861 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3862 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3863
3864 // In order to identify the right initializer we need to match the
3865 // declaration used by the mapping logic. In some cases we may get
3866 // OMPCapturedExprDecl that refers to the original declaration.
3867 const ValueDecl *MatchingVD = OrigVD;
3868 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3869 // OMPCapturedExprDecl are used to privative fields of the current
3870 // structure.
3871 auto *ME = cast<MemberExpr>(OED->getInit());
3872 assert(isa<CXXThisExpr>(ME->getBase()) &&
3873 "Base should be the current struct!");
3874 MatchingVD = ME->getMemberDecl();
3875 }
3876
3877 // If we don't have information about the current list item, move on to
3878 // the next one.
3879 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3880 if (InitAddrIt == CaptureDeviceAddrMap.end())
3881 continue;
3882
3883 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3884 // Initialize the temporary initialization variable with the address we
3885 // get from the runtime library. We have to cast the source address
3886 // because it is always a void *. References are materialized in the
3887 // privatization scope, so the initialization here disregards the fact
3888 // the original variable is a reference.
3889 QualType AddrQTy =
3890 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3891 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3892 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3893 setAddrOfLocalVar(InitVD, InitAddr);
3894
3895 // Emit private declaration, it will be initialized by the value we
3896 // declaration we just added to the local declarations map.
3897 EmitDecl(*PvtVD);
3898
3899 // The initialization variables reached its purpose in the emission
3900 // ofthe previous declaration, so we don't need it anymore.
3901 LocalDeclMap.erase(InitVD);
3902
3903 // Return the address of the private variable.
3904 return GetAddrOfLocalVar(PvtVD);
3905 });
3906 assert(IsRegistered && "firstprivate var already registered as private");
3907 // Silence the warning about unused variable.
3908 (void)IsRegistered;
3909
3910 ++OrigVarIt;
3911 ++InitIt;
3912 }
3913}
3914
Michael Wong65f367f2015-07-21 13:44:28 +00003915// Generate the instructions for '#pragma omp target data' directive.
3916void CodeGenFunction::EmitOMPTargetDataDirective(
3917 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003918 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3919
3920 // Create a pre/post action to signal the privatization of the device pointer.
3921 // This action can be replaced by the OpenMP runtime code generation to
3922 // deactivate privatization.
3923 bool PrivatizeDevicePointers = false;
3924 class DevicePointerPrivActionTy : public PrePostActionTy {
3925 bool &PrivatizeDevicePointers;
3926
3927 public:
3928 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3929 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3930 void Enter(CodeGenFunction &CGF) override {
3931 PrivatizeDevicePointers = true;
3932 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003933 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003934 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3935
3936 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3937 CodeGenFunction &CGF, PrePostActionTy &Action) {
3938 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3939 CGF.EmitStmt(
3940 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3941 };
3942
3943 // Codegen that selects wheather to generate the privatization code or not.
3944 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3945 &InnermostCodeGen](CodeGenFunction &CGF,
3946 PrePostActionTy &Action) {
3947 RegionCodeGenTy RCG(InnermostCodeGen);
3948 PrivatizeDevicePointers = false;
3949
3950 // Call the pre-action to change the status of PrivatizeDevicePointers if
3951 // needed.
3952 Action.Enter(CGF);
3953
3954 if (PrivatizeDevicePointers) {
3955 OMPPrivateScope PrivateScope(CGF);
3956 // Emit all instances of the use_device_ptr clause.
3957 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3958 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3959 Info.CaptureDeviceAddrMap);
3960 (void)PrivateScope.Privatize();
3961 RCG(CGF);
3962 } else
3963 RCG(CGF);
3964 };
3965
3966 // Forward the provided action to the privatization codegen.
3967 RegionCodeGenTy PrivRCG(PrivCodeGen);
3968 PrivRCG.setAction(Action);
3969
3970 // Notwithstanding the body of the region is emitted as inlined directive,
3971 // we don't use an inline scope as changes in the references inside the
3972 // region are expected to be visible outside, so we do not privative them.
3973 OMPLexicalScope Scope(CGF, S);
3974 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3975 PrivRCG);
3976 };
3977
3978 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003979
3980 // If we don't have target devices, don't bother emitting the data mapping
3981 // code.
3982 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003983 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003984 return;
3985 }
3986
3987 // Check if we have any if clause associated with the directive.
3988 const Expr *IfCond = nullptr;
3989 if (auto *C = S.getSingleClause<OMPIfClause>())
3990 IfCond = C->getCondition();
3991
3992 // Check if we have any device clause associated with the directive.
3993 const Expr *Device = nullptr;
3994 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3995 Device = C->getDevice();
3996
Samuel Antaocc10b852016-07-28 14:23:26 +00003997 // Set the action to signal privatization of device pointers.
3998 RCG.setAction(PrivAction);
3999
4000 // Emit region code.
4001 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4002 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004003}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004004
Samuel Antaodf67fc42016-01-19 19:15:56 +00004005void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4006 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004007 // If we don't have target devices, don't bother emitting the data mapping
4008 // code.
4009 if (CGM.getLangOpts().OMPTargetTriples.empty())
4010 return;
4011
4012 // Check if we have any if clause associated with the directive.
4013 const Expr *IfCond = nullptr;
4014 if (auto *C = S.getSingleClause<OMPIfClause>())
4015 IfCond = C->getCondition();
4016
4017 // Check if we have any device clause associated with the directive.
4018 const Expr *Device = nullptr;
4019 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4020 Device = C->getDevice();
4021
Samuel Antao8d2d7302016-05-26 18:30:22 +00004022 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004023}
4024
Samuel Antao72590762016-01-19 20:04:50 +00004025void CodeGenFunction::EmitOMPTargetExitDataDirective(
4026 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004027 // If we don't have target devices, don't bother emitting the data mapping
4028 // code.
4029 if (CGM.getLangOpts().OMPTargetTriples.empty())
4030 return;
4031
4032 // Check if we have any if clause associated with the directive.
4033 const Expr *IfCond = nullptr;
4034 if (auto *C = S.getSingleClause<OMPIfClause>())
4035 IfCond = C->getCondition();
4036
4037 // Check if we have any device clause associated with the directive.
4038 const Expr *Device = nullptr;
4039 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4040 Device = C->getDevice();
4041
Samuel Antao8d2d7302016-05-26 18:30:22 +00004042 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004043}
4044
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004045static void emitTargetParallelRegion(CodeGenFunction &CGF,
4046 const OMPTargetParallelDirective &S,
4047 PrePostActionTy &Action) {
4048 // Get the captured statement associated with the 'parallel' region.
4049 auto *CS = S.getCapturedStmt(OMPD_parallel);
4050 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004051 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4052 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4053 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4054 CGF.EmitOMPPrivateClause(S, PrivateScope);
4055 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4056 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004057 // TODO: Add support for clauses.
4058 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004059 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004060 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004061 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4062 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004063 emitPostUpdateForReductionClause(
4064 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004065}
4066
4067void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4068 CodeGenModule &CGM, StringRef ParentName,
4069 const OMPTargetParallelDirective &S) {
4070 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4071 emitTargetParallelRegion(CGF, S, Action);
4072 };
4073 llvm::Function *Fn;
4074 llvm::Constant *Addr;
4075 // Emit target region as a standalone region.
4076 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4077 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4078 assert(Fn && Addr && "Target device function emission failed.");
4079}
4080
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004081void CodeGenFunction::EmitOMPTargetParallelDirective(
4082 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004083 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4084 emitTargetParallelRegion(CGF, S, Action);
4085 };
4086 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004087}
4088
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004089void CodeGenFunction::EmitOMPTargetParallelForDirective(
4090 const OMPTargetParallelForDirective &S) {
4091 // TODO: codegen for target parallel for.
4092}
4093
Alexey Bataev7292c292016-04-25 12:22:29 +00004094/// Emit a helper variable and return corresponding lvalue.
4095static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4096 const ImplicitParamDecl *PVD,
4097 CodeGenFunction::OMPPrivateScope &Privates) {
4098 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4099 Privates.addPrivate(
4100 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4101}
4102
4103void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4104 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4105 // Emit outlined function for task construct.
4106 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4107 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4108 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4109 const Expr *IfCond = nullptr;
4110 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4111 if (C->getNameModifier() == OMPD_unknown ||
4112 C->getNameModifier() == OMPD_taskloop) {
4113 IfCond = C->getCondition();
4114 break;
4115 }
4116 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004117
4118 OMPTaskDataTy Data;
4119 // Check if taskloop must be emitted without taskgroup.
4120 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004121 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004122 Data.Tied = true;
4123 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004124 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4125 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004126 Data.Schedule.setInt(/*IntVal=*/false);
4127 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004128 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4129 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004130 Data.Schedule.setInt(/*IntVal=*/true);
4131 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004132 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004133
4134 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4135 // if (PreCond) {
4136 // for (IV in 0..LastIteration) BODY;
4137 // <Final counter/linear vars updates>;
4138 // }
4139 //
4140
4141 // Emit: if (PreCond) - begin.
4142 // If the condition constant folds and can be elided, avoid emitting the
4143 // whole loop.
4144 bool CondConstant;
4145 llvm::BasicBlock *ContBlock = nullptr;
4146 OMPLoopScope PreInitScope(CGF, S);
4147 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4148 if (!CondConstant)
4149 return;
4150 } else {
4151 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4152 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4153 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4154 CGF.getProfileCount(&S));
4155 CGF.EmitBlock(ThenBlock);
4156 CGF.incrementProfileCounter(&S);
4157 }
4158
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004159 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4160 CGF.EmitOMPSimdInit(S);
4161
Alexey Bataev7292c292016-04-25 12:22:29 +00004162 OMPPrivateScope LoopScope(CGF);
4163 // Emit helper vars inits.
4164 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4165 auto *I = CS->getCapturedDecl()->param_begin();
4166 auto *LBP = std::next(I, LowerBound);
4167 auto *UBP = std::next(I, UpperBound);
4168 auto *STP = std::next(I, Stride);
4169 auto *LIP = std::next(I, LastIter);
4170 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4171 LoopScope);
4172 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4173 LoopScope);
4174 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4175 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4176 LoopScope);
4177 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004178 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004179 (void)LoopScope.Privatize();
4180 // Emit the loop iteration variable.
4181 const Expr *IVExpr = S.getIterationVariable();
4182 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4183 CGF.EmitVarDecl(*IVDecl);
4184 CGF.EmitIgnoredExpr(S.getInit());
4185
4186 // Emit the iterations count variable.
4187 // If it is not a variable, Sema decided to calculate iterations count on
4188 // each iteration (e.g., it is foldable into a constant).
4189 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4190 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4191 // Emit calculation of the iterations count.
4192 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4193 }
4194
4195 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4196 S.getInc(),
4197 [&S](CodeGenFunction &CGF) {
4198 CGF.EmitOMPLoopBody(S, JumpDest());
4199 CGF.EmitStopPoint(&S);
4200 },
4201 [](CodeGenFunction &) {});
4202 // Emit: if (PreCond) - end.
4203 if (ContBlock) {
4204 CGF.EmitBranch(ContBlock);
4205 CGF.EmitBlock(ContBlock, true);
4206 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004207 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4208 if (HasLastprivateClause) {
4209 CGF.EmitOMPLastprivateClauseFinal(
4210 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4211 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4212 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4213 (*LIP)->getType(), S.getLocStart())));
4214 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004215 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004216 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4217 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4218 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004219 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4220 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004221 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4222 OutlinedFn, SharedsTy,
4223 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004224 };
4225 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4226 CodeGen);
4227 };
Alexey Bataev33446032017-07-12 18:09:32 +00004228 if (Data.Nogroup)
4229 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4230 else {
4231 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4232 *this,
4233 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4234 PrePostActionTy &Action) {
4235 Action.Enter(CGF);
4236 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4237 },
4238 S.getLocStart());
4239 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004240}
4241
Alexey Bataev49f6e782015-12-01 04:18:41 +00004242void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004243 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004244}
4245
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004246void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4247 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004248 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004249}
Samuel Antao686c70c2016-05-26 17:30:50 +00004250
4251// Generate the instructions for '#pragma omp target update' directive.
4252void CodeGenFunction::EmitOMPTargetUpdateDirective(
4253 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004254 // If we don't have target devices, don't bother emitting the data mapping
4255 // code.
4256 if (CGM.getLangOpts().OMPTargetTriples.empty())
4257 return;
4258
4259 // Check if we have any if clause associated with the directive.
4260 const Expr *IfCond = nullptr;
4261 if (auto *C = S.getSingleClause<OMPIfClause>())
4262 IfCond = C->getCondition();
4263
4264 // Check if we have any device clause associated with the directive.
4265 const Expr *Device = nullptr;
4266 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4267 Device = C->getDevice();
4268
4269 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004270}