blob: 7213c4d079eb1eecaf2121942673598c7547de53 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
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 provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "llvm/ADT/ArrayRef.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000021#include "llvm/Bitcode/ReaderWriter.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000026#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000028#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000029
30using namespace clang;
31using namespace CodeGen;
32
Benjamin Kramerc52193f2014-10-10 13:57:57 +000033namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000035class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000037 /// \brief Kinds of OpenMP regions used in codegen.
38 enum CGOpenMPRegionKind {
39 /// \brief Region with outlined function for standalone 'parallel'
40 /// directive.
41 ParallelOutlinedRegion,
42 /// \brief Region with outlined function for standalone 'task' directive.
43 TaskOutlinedRegion,
44 /// \brief Region for constructs that do not require function outlining,
45 /// like 'for', 'sections', 'atomic' etc. directives.
46 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000047 /// \brief Region with outlined function for standalone 'target' directive.
48 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 };
Alexey Bataev18095712014-10-10 12:19:54 +000050
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 CGOpenMPRegionInfo(const CapturedStmt &CS,
52 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000055 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057
58 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000061 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000063
64 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000065 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000069 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000071 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000072 /// \return LValue for thread id variable. This LValue always has type int32*.
73 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000074
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000076
Alexey Bataev81c7ea02015-07-03 09:56:58 +000077 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
78
Alexey Bataev25e5b442015-09-15 12:52:43 +000079 bool hasCancel() const { return HasCancel; }
80
Alexey Bataev18095712014-10-10 12:19:54 +000081 static bool classof(const CGCapturedStmtInfo *Info) {
82 return Info->getKind() == CR_OpenMP;
83 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000084
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000085protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000086 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000087 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000088 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000089 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090};
Alexey Bataev18095712014-10-10 12:19:54 +000091
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092/// \brief API for captured statement code generation in OpenMP constructs.
93class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
94public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000096 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +000097 OpenMPDirectiveKind Kind, bool HasCancel)
98 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
99 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
102 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000103
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000104 /// \brief Get a variable or parameter for storing global thread id
105 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000106 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000107
Alexey Bataev18095712014-10-10 12:19:54 +0000108 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000109 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000110
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000111 static bool classof(const CGCapturedStmtInfo *Info) {
112 return CGOpenMPRegionInfo::classof(Info) &&
113 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
114 ParallelOutlinedRegion;
115 }
116
Alexey Bataev18095712014-10-10 12:19:54 +0000117private:
118 /// \brief A variable or parameter storing global thread id for OpenMP
119 /// constructs.
120 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000121};
122
Alexey Bataev62b63b12015-03-10 07:28:44 +0000123/// \brief API for captured statement code generation in OpenMP constructs.
124class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
125public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000126 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000127 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000128 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000129 OpenMPDirectiveKind Kind, bool HasCancel)
130 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000131 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
133 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000134
Alexey Bataev62b63b12015-03-10 07:28:44 +0000135 /// \brief Get a variable or parameter for storing global thread id
136 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000137 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000138
139 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000140 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000141
Alexey Bataev62b63b12015-03-10 07:28:44 +0000142 /// \brief Get the name of the capture helper.
143 StringRef getHelperName() const override { return ".omp_outlined."; }
144
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000145 static bool classof(const CGCapturedStmtInfo *Info) {
146 return CGOpenMPRegionInfo::classof(Info) &&
147 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
148 TaskOutlinedRegion;
149 }
150
Alexey Bataev62b63b12015-03-10 07:28:44 +0000151private:
152 /// \brief A variable or parameter storing global thread id for OpenMP
153 /// constructs.
154 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000155};
156
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000157/// \brief API for inlined captured statement code generation in OpenMP
158/// constructs.
159class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
160public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000161 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000162 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000163 OpenMPDirectiveKind Kind, bool HasCancel)
164 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
165 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000166 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000167
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000168 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000169 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000170 if (OuterRegionInfo)
171 return OuterRegionInfo->getContextValue();
172 llvm_unreachable("No context value for inlined OpenMP region");
173 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000174
Hans Wennborg7eb54642015-09-10 17:07:54 +0000175 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000176 if (OuterRegionInfo) {
177 OuterRegionInfo->setContextValue(V);
178 return;
179 }
180 llvm_unreachable("No context value for inlined OpenMP region");
181 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000182
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000183 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000184 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 if (OuterRegionInfo)
186 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000187 // If there is no outer outlined region,no need to lookup in a list of
188 // captured variables, we can use the original one.
189 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000190 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000191
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000193 if (OuterRegionInfo)
194 return OuterRegionInfo->getThisFieldDecl();
195 return nullptr;
196 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000197
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000198 /// \brief Get a variable or parameter for storing global thread id
199 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000200 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000201 if (OuterRegionInfo)
202 return OuterRegionInfo->getThreadIDVariable();
203 return nullptr;
204 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000205
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000206 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000207 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000208 if (auto *OuterRegionInfo = getOldCSI())
209 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000210 llvm_unreachable("No helper name for inlined OpenMP construct");
211 }
212
213 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
214
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000215 static bool classof(const CGCapturedStmtInfo *Info) {
216 return CGOpenMPRegionInfo::classof(Info) &&
217 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
218 }
219
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000220private:
221 /// \brief CodeGen info about outer OpenMP region.
222 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
223 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000224};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225
Samuel Antaobed3c462015-10-02 16:14:20 +0000226/// \brief API for captured statement code generation in OpenMP target
227/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000228/// captured fields. The name of the target region has to be unique in a given
229/// application so it is provided by the client, because only the client has
230/// the information to generate that.
Samuel Antaobed3c462015-10-02 16:14:20 +0000231class CGOpenMPTargetRegionInfo : public CGOpenMPRegionInfo {
232public:
233 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000234 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000235 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000236 /*HasCancel=*/false),
237 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000238
239 /// \brief This is unused for target regions because each starts executing
240 /// with a single thread.
241 const VarDecl *getThreadIDVariable() const override { return nullptr; }
242
243 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000244 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000245
246 static bool classof(const CGCapturedStmtInfo *Info) {
247 return CGOpenMPRegionInfo::classof(Info) &&
248 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
249 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000250
251private:
252 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000253};
254
Samuel Antaob68e2db2016-03-03 16:20:23 +0000255static void EmptyCodeGen(CodeGenFunction &) {
256 llvm_unreachable("No codegen for expressions");
257}
258/// \brief API for generation of expressions captured in a innermost OpenMP
259/// region.
260class CGOpenMPInnerExprInfo : public CGOpenMPInlinedRegionInfo {
261public:
262 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
263 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
264 OMPD_unknown,
265 /*HasCancel=*/false),
266 PrivScope(CGF) {
267 // Make sure the globals captured in the provided statement are local by
268 // using the privatization logic. We assume the same variable is not
269 // captured more than once.
270 for (auto &C : CS.captures()) {
271 if (!C.capturesVariable() && !C.capturesVariableByCopy())
272 continue;
273
274 const VarDecl *VD = C.getCapturedVar();
275 if (VD->isLocalVarDeclOrParm())
276 continue;
277
278 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
279 /*RefersToEnclosingVariableOrCapture=*/false,
280 VD->getType().getNonReferenceType(), VK_LValue,
281 SourceLocation());
282 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
283 return CGF.EmitLValue(&DRE).getAddress();
284 });
285 }
286 (void)PrivScope.Privatize();
287 }
288
289 /// \brief Lookup the captured field decl for a variable.
290 const FieldDecl *lookup(const VarDecl *VD) const override {
291 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
292 return FD;
293 return nullptr;
294 }
295
296 /// \brief Emit the captured statement body.
297 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
298 llvm_unreachable("No body for expressions");
299 }
300
301 /// \brief Get a variable or parameter for storing global thread id
302 /// inside OpenMP construct.
303 const VarDecl *getThreadIDVariable() const override {
304 llvm_unreachable("No thread id for expressions");
305 }
306
307 /// \brief Get the name of the capture helper.
308 StringRef getHelperName() const override {
309 llvm_unreachable("No helper name for expressions");
310 }
311
312 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
313
314private:
315 /// Private scope to capture global variables.
316 CodeGenFunction::OMPPrivateScope PrivScope;
317};
318
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000319/// \brief RAII for emitting code of OpenMP constructs.
320class InlinedOpenMPRegionRAII {
321 CodeGenFunction &CGF;
322
323public:
324 /// \brief Constructs region for combined constructs.
325 /// \param CodeGen Code generation sequence for combined directives. Includes
326 /// a list of functions used for code generation of implicitly inlined
327 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000328 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000329 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000330 : CGF(CGF) {
331 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000332 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
333 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000334 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000335
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000336 ~InlinedOpenMPRegionRAII() {
337 // Restore original CapturedStmtInfo only if we're done with code emission.
338 auto *OldCSI =
339 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
340 delete CGF.CapturedStmtInfo;
341 CGF.CapturedStmtInfo = OldCSI;
342 }
343};
344
Alexey Bataev50b3c952016-02-19 10:38:26 +0000345/// \brief Values for bit flags used in the ident_t to describe the fields.
346/// All enumeric elements are named and described in accordance with the code
347/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
348enum OpenMPLocationFlags {
349 /// \brief Use trampoline for internal microtask.
350 OMP_IDENT_IMD = 0x01,
351 /// \brief Use c-style ident structure.
352 OMP_IDENT_KMPC = 0x02,
353 /// \brief Atomic reduction option for kmpc_reduce.
354 OMP_ATOMIC_REDUCE = 0x10,
355 /// \brief Explicit 'barrier' directive.
356 OMP_IDENT_BARRIER_EXPL = 0x20,
357 /// \brief Implicit barrier in code.
358 OMP_IDENT_BARRIER_IMPL = 0x40,
359 /// \brief Implicit barrier in 'for' directive.
360 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
361 /// \brief Implicit barrier in 'sections' directive.
362 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
363 /// \brief Implicit barrier in 'single' directive.
364 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
365};
366
367/// \brief Describes ident structure that describes a source location.
368/// All descriptions are taken from
369/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
370/// Original structure:
371/// typedef struct ident {
372/// kmp_int32 reserved_1; /**< might be used in Fortran;
373/// see above */
374/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
375/// KMP_IDENT_KMPC identifies this union
376/// member */
377/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
378/// see above */
379///#if USE_ITT_BUILD
380/// /* but currently used for storing
381/// region-specific ITT */
382/// /* contextual information. */
383///#endif /* USE_ITT_BUILD */
384/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
385/// C++ */
386/// char const *psource; /**< String describing the source location.
387/// The string is composed of semi-colon separated
388// fields which describe the source file,
389/// the function and a pair of line numbers that
390/// delimit the construct.
391/// */
392/// } ident_t;
393enum IdentFieldIndex {
394 /// \brief might be used in Fortran
395 IdentField_Reserved_1,
396 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
397 IdentField_Flags,
398 /// \brief Not really used in Fortran any more
399 IdentField_Reserved_2,
400 /// \brief Source[4] in Fortran, do not use for C++
401 IdentField_Reserved_3,
402 /// \brief String describing the source location. The string is composed of
403 /// semi-colon separated fields which describe the source file, the function
404 /// and a pair of line numbers that delimit the construct.
405 IdentField_PSource
406};
407
408/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
409/// the enum sched_type in kmp.h).
410enum OpenMPSchedType {
411 /// \brief Lower bound for default (unordered) versions.
412 OMP_sch_lower = 32,
413 OMP_sch_static_chunked = 33,
414 OMP_sch_static = 34,
415 OMP_sch_dynamic_chunked = 35,
416 OMP_sch_guided_chunked = 36,
417 OMP_sch_runtime = 37,
418 OMP_sch_auto = 38,
419 /// \brief Lower bound for 'ordered' versions.
420 OMP_ord_lower = 64,
421 OMP_ord_static_chunked = 65,
422 OMP_ord_static = 66,
423 OMP_ord_dynamic_chunked = 67,
424 OMP_ord_guided_chunked = 68,
425 OMP_ord_runtime = 69,
426 OMP_ord_auto = 70,
427 OMP_sch_default = OMP_sch_static,
428};
429
430enum OpenMPRTLFunction {
431 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
432 /// kmpc_micro microtask, ...);
433 OMPRTL__kmpc_fork_call,
434 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
435 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
436 OMPRTL__kmpc_threadprivate_cached,
437 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
438 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
439 OMPRTL__kmpc_threadprivate_register,
440 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
441 OMPRTL__kmpc_global_thread_num,
442 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
443 // kmp_critical_name *crit);
444 OMPRTL__kmpc_critical,
445 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
446 // global_tid, kmp_critical_name *crit, uintptr_t hint);
447 OMPRTL__kmpc_critical_with_hint,
448 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
449 // kmp_critical_name *crit);
450 OMPRTL__kmpc_end_critical,
451 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
452 // global_tid);
453 OMPRTL__kmpc_cancel_barrier,
454 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
455 OMPRTL__kmpc_barrier,
456 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
457 OMPRTL__kmpc_for_static_fini,
458 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
459 // global_tid);
460 OMPRTL__kmpc_serialized_parallel,
461 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
462 // global_tid);
463 OMPRTL__kmpc_end_serialized_parallel,
464 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
465 // kmp_int32 num_threads);
466 OMPRTL__kmpc_push_num_threads,
467 // Call to void __kmpc_flush(ident_t *loc);
468 OMPRTL__kmpc_flush,
469 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
470 OMPRTL__kmpc_master,
471 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
472 OMPRTL__kmpc_end_master,
473 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
474 // int end_part);
475 OMPRTL__kmpc_omp_taskyield,
476 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
477 OMPRTL__kmpc_single,
478 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
479 OMPRTL__kmpc_end_single,
480 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
481 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
482 // kmp_routine_entry_t *task_entry);
483 OMPRTL__kmpc_omp_task_alloc,
484 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
485 // new_task);
486 OMPRTL__kmpc_omp_task,
487 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
488 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
489 // kmp_int32 didit);
490 OMPRTL__kmpc_copyprivate,
491 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
492 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
493 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
494 OMPRTL__kmpc_reduce,
495 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
496 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
497 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
498 // *lck);
499 OMPRTL__kmpc_reduce_nowait,
500 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
501 // kmp_critical_name *lck);
502 OMPRTL__kmpc_end_reduce,
503 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
504 // kmp_critical_name *lck);
505 OMPRTL__kmpc_end_reduce_nowait,
506 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
507 // kmp_task_t * new_task);
508 OMPRTL__kmpc_omp_task_begin_if0,
509 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
510 // kmp_task_t * new_task);
511 OMPRTL__kmpc_omp_task_complete_if0,
512 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
513 OMPRTL__kmpc_ordered,
514 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
515 OMPRTL__kmpc_end_ordered,
516 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
517 // global_tid);
518 OMPRTL__kmpc_omp_taskwait,
519 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
520 OMPRTL__kmpc_taskgroup,
521 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
522 OMPRTL__kmpc_end_taskgroup,
523 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
524 // int proc_bind);
525 OMPRTL__kmpc_push_proc_bind,
526 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
527 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
528 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
529 OMPRTL__kmpc_omp_task_with_deps,
530 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
531 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
532 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
533 OMPRTL__kmpc_omp_wait_deps,
534 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
535 // global_tid, kmp_int32 cncl_kind);
536 OMPRTL__kmpc_cancellationpoint,
537 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
538 // kmp_int32 cncl_kind);
539 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000540 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
541 // kmp_int32 num_teams, kmp_int32 thread_limit);
542 OMPRTL__kmpc_push_num_teams,
543 /// \brief Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc,
544 /// kmpc_micro microtask, ...);
545 OMPRTL__kmpc_fork_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000546
547 //
548 // Offloading related calls
549 //
550 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
551 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
552 // *arg_types);
553 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000554 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
555 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
556 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
557 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000558 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
559 OMPRTL__tgt_register_lib,
560 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
561 OMPRTL__tgt_unregister_lib,
562};
563
Hans Wennborg7eb54642015-09-10 17:07:54 +0000564} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000565
566LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000567 return CGF.EmitLoadOfPointerLValue(
568 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
569 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000570}
571
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000572void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000573 if (!CGF.HaveInsertPoint())
574 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000575 // 1.2.2 OpenMP Language Terminology
576 // Structured block - An executable statement with a single entry at the
577 // top and a single exit at the bottom.
578 // The point of exit cannot be a branch out of the structured block.
579 // longjmp() and throw() must not violate the entry/exit criteria.
580 CGF.EHStack.pushTerminate();
581 {
582 CodeGenFunction::RunCleanupsScope Scope(CGF);
583 CodeGen(CGF);
584 }
585 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000586}
587
Alexey Bataev62b63b12015-03-10 07:28:44 +0000588LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
589 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000590 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
591 getThreadIDVariable()->getType(),
592 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000593}
594
Alexey Bataev9959db52014-05-06 10:08:46 +0000595CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Samuel Antaoee8fb302016-01-06 13:42:12 +0000596 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr),
597 OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000598 IdentTy = llvm::StructType::create(
599 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
600 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000601 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000602 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000603 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
604 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000605 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000606 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000607
608 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000609}
610
Alexey Bataev91797552015-03-18 04:13:55 +0000611void CGOpenMPRuntime::clear() {
612 InternalVars.clear();
613}
614
John McCall7f416cc2015-09-08 08:05:57 +0000615// Layout information for ident_t.
616static CharUnits getIdentAlign(CodeGenModule &CGM) {
617 return CGM.getPointerAlign();
618}
619static CharUnits getIdentSize(CodeGenModule &CGM) {
620 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
621 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
622}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000623static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000624 // All the fields except the last are i32, so this works beautifully.
625 return unsigned(Field) * CharUnits::fromQuantity(4);
626}
627static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000628 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000629 const llvm::Twine &Name = "") {
630 auto Offset = getOffsetOfIdentField(Field);
631 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
632}
633
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000634llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000635 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
636 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000637 assert(ThreadIDVar->getType()->isPointerType() &&
638 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000639 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
640 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000641 bool HasCancel = false;
642 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
643 HasCancel = OPD->hasCancel();
644 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
645 HasCancel = OPSD->hasCancel();
646 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
647 HasCancel = OPFD->hasCancel();
648 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
649 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000650 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000651 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000652}
653
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000654llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
655 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
656 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000657 assert(!ThreadIDVar->getType()->isPointerType() &&
658 "thread id variable must be of type kmp_int32 for tasks");
659 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
660 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000661 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000662 InnermostKind,
663 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000664 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000665 return CGF.GenerateCapturedStmtFunction(*CS);
666}
667
Alexey Bataev50b3c952016-02-19 10:38:26 +0000668Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000669 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000670 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000671 if (!Entry) {
672 if (!DefaultOpenMPPSource) {
673 // Initialize default location for psource field of ident_t structure of
674 // all ident_t objects. Format is ";file;function;line;column;;".
675 // Taken from
676 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
677 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000678 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000679 DefaultOpenMPPSource =
680 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
681 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000682 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
683 CGM.getModule(), IdentTy, /*isConstant*/ true,
684 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000685 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000686 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000687
688 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000689 llvm::Constant *Values[] = {Zero,
690 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
691 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000692 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
693 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000694 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000695 }
John McCall7f416cc2015-09-08 08:05:57 +0000696 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000697}
698
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000699llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
700 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000701 unsigned Flags) {
702 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000703 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000704 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000705 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000706 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000707
708 assert(CGF.CurFn && "No function in current CodeGenFunction.");
709
John McCall7f416cc2015-09-08 08:05:57 +0000710 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000711 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
712 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000713 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
714
Alexander Musmanc6388682014-12-15 07:07:06 +0000715 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
716 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000717 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000718 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000719 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
720 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000721 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000722 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000723 LocValue = AI;
724
725 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
726 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000727 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000728 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000729 }
730
731 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000732 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000733
Alexey Bataevf002aca2014-05-30 05:48:40 +0000734 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
735 if (OMPDebugLoc == nullptr) {
736 SmallString<128> Buffer2;
737 llvm::raw_svector_ostream OS2(Buffer2);
738 // Build debug location
739 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
740 OS2 << ";" << PLoc.getFilename() << ";";
741 if (const FunctionDecl *FD =
742 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
743 OS2 << FD->getQualifiedNameAsString();
744 }
745 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
746 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
747 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000748 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000749 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000750 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
751
John McCall7f416cc2015-09-08 08:05:57 +0000752 // Our callers always pass this to a runtime function, so for
753 // convenience, go ahead and return a naked pointer.
754 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000755}
756
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000757llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
758 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000759 assert(CGF.CurFn && "No function in current CodeGenFunction.");
760
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000761 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000762 // Check whether we've already cached a load of the thread id in this
763 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000764 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000765 if (I != OpenMPLocThreadIDMap.end()) {
766 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000767 if (ThreadID != nullptr)
768 return ThreadID;
769 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000770 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000771 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000772 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000773 // Check if this an outlined function with thread id passed as argument.
774 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000775 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
776 // If value loaded in entry block, cache it and use it everywhere in
777 // function.
778 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
779 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
780 Elem.second.ThreadID = ThreadID;
781 }
782 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000783 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000784 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000785
786 // This is not an outlined function region - need to call __kmpc_int32
787 // kmpc_global_thread_num(ident_t *loc).
788 // Generate thread id value and cache this value for use across the
789 // function.
790 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
791 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
792 ThreadID =
793 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
794 emitUpdateLocation(CGF, Loc));
795 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
796 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000797 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000798}
799
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000800void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000801 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000802 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
803 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000804}
805
806llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
807 return llvm::PointerType::getUnqual(IdentTy);
808}
809
810llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
811 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
812}
813
814llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +0000815CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000816 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +0000817 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000818 case OMPRTL__kmpc_fork_call: {
819 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
820 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000821 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
822 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000823 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000824 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000825 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
826 break;
827 }
828 case OMPRTL__kmpc_global_thread_num: {
829 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000830 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000831 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000832 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000833 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
834 break;
835 }
Alexey Bataev97720002014-11-11 04:05:39 +0000836 case OMPRTL__kmpc_threadprivate_cached: {
837 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
838 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
839 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
840 CGM.VoidPtrTy, CGM.SizeTy,
841 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
842 llvm::FunctionType *FnTy =
843 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
844 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
845 break;
846 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000847 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000848 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
849 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000850 llvm::Type *TypeParams[] = {
851 getIdentTyPointerTy(), CGM.Int32Ty,
852 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
853 llvm::FunctionType *FnTy =
854 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
855 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
856 break;
857 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000858 case OMPRTL__kmpc_critical_with_hint: {
859 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
860 // kmp_critical_name *crit, uintptr_t hint);
861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
862 llvm::PointerType::getUnqual(KmpCriticalNameTy),
863 CGM.IntPtrTy};
864 llvm::FunctionType *FnTy =
865 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
866 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
867 break;
868 }
Alexey Bataev97720002014-11-11 04:05:39 +0000869 case OMPRTL__kmpc_threadprivate_register: {
870 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
871 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
872 // typedef void *(*kmpc_ctor)(void *);
873 auto KmpcCtorTy =
874 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
875 /*isVarArg*/ false)->getPointerTo();
876 // typedef void *(*kmpc_cctor)(void *, void *);
877 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
878 auto KmpcCopyCtorTy =
879 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
880 /*isVarArg*/ false)->getPointerTo();
881 // typedef void (*kmpc_dtor)(void *);
882 auto KmpcDtorTy =
883 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
884 ->getPointerTo();
885 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
886 KmpcCopyCtorTy, KmpcDtorTy};
887 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
888 /*isVarArg*/ false);
889 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
890 break;
891 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000892 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000893 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
894 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000895 llvm::Type *TypeParams[] = {
896 getIdentTyPointerTy(), CGM.Int32Ty,
897 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
898 llvm::FunctionType *FnTy =
899 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
900 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
901 break;
902 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000903 case OMPRTL__kmpc_cancel_barrier: {
904 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
905 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
907 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000908 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
909 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000910 break;
911 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000912 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000913 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000914 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
915 llvm::FunctionType *FnTy =
916 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
917 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
918 break;
919 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000920 case OMPRTL__kmpc_for_static_fini: {
921 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
922 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
923 llvm::FunctionType *FnTy =
924 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
925 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
926 break;
927 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000928 case OMPRTL__kmpc_push_num_threads: {
929 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
930 // kmp_int32 num_threads)
931 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
932 CGM.Int32Ty};
933 llvm::FunctionType *FnTy =
934 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
935 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
936 break;
937 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000938 case OMPRTL__kmpc_serialized_parallel: {
939 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
940 // global_tid);
941 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
942 llvm::FunctionType *FnTy =
943 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
944 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
945 break;
946 }
947 case OMPRTL__kmpc_end_serialized_parallel: {
948 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
949 // global_tid);
950 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
951 llvm::FunctionType *FnTy =
952 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
953 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
954 break;
955 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000956 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000957 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000958 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
959 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000960 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000961 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
962 break;
963 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000964 case OMPRTL__kmpc_master: {
965 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
967 llvm::FunctionType *FnTy =
968 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
969 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
970 break;
971 }
972 case OMPRTL__kmpc_end_master: {
973 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
974 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
975 llvm::FunctionType *FnTy =
976 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
977 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
978 break;
979 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000980 case OMPRTL__kmpc_omp_taskyield: {
981 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
982 // int end_part);
983 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
984 llvm::FunctionType *FnTy =
985 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
986 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
987 break;
988 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000989 case OMPRTL__kmpc_single: {
990 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
991 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
992 llvm::FunctionType *FnTy =
993 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
994 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
995 break;
996 }
997 case OMPRTL__kmpc_end_single: {
998 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
999 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1000 llvm::FunctionType *FnTy =
1001 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1002 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1003 break;
1004 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001005 case OMPRTL__kmpc_omp_task_alloc: {
1006 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1007 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1008 // kmp_routine_entry_t *task_entry);
1009 assert(KmpRoutineEntryPtrTy != nullptr &&
1010 "Type kmp_routine_entry_t must be created.");
1011 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1012 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1013 // Return void * and then cast to particular kmp_task_t type.
1014 llvm::FunctionType *FnTy =
1015 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1016 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1017 break;
1018 }
1019 case OMPRTL__kmpc_omp_task: {
1020 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1021 // *new_task);
1022 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1023 CGM.VoidPtrTy};
1024 llvm::FunctionType *FnTy =
1025 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1026 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1027 break;
1028 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001029 case OMPRTL__kmpc_copyprivate: {
1030 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001031 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001032 // kmp_int32 didit);
1033 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1034 auto *CpyFnTy =
1035 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001036 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001037 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1038 CGM.Int32Ty};
1039 llvm::FunctionType *FnTy =
1040 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1041 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1042 break;
1043 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001044 case OMPRTL__kmpc_reduce: {
1045 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1046 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1047 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1048 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1049 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1050 /*isVarArg=*/false);
1051 llvm::Type *TypeParams[] = {
1052 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1053 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1054 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1055 llvm::FunctionType *FnTy =
1056 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1057 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1058 break;
1059 }
1060 case OMPRTL__kmpc_reduce_nowait: {
1061 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1062 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1063 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1064 // *lck);
1065 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1066 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1067 /*isVarArg=*/false);
1068 llvm::Type *TypeParams[] = {
1069 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1070 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1071 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1072 llvm::FunctionType *FnTy =
1073 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1074 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1075 break;
1076 }
1077 case OMPRTL__kmpc_end_reduce: {
1078 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1079 // kmp_critical_name *lck);
1080 llvm::Type *TypeParams[] = {
1081 getIdentTyPointerTy(), CGM.Int32Ty,
1082 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1083 llvm::FunctionType *FnTy =
1084 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1085 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1086 break;
1087 }
1088 case OMPRTL__kmpc_end_reduce_nowait: {
1089 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1090 // kmp_critical_name *lck);
1091 llvm::Type *TypeParams[] = {
1092 getIdentTyPointerTy(), CGM.Int32Ty,
1093 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1094 llvm::FunctionType *FnTy =
1095 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1096 RTLFn =
1097 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1098 break;
1099 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001100 case OMPRTL__kmpc_omp_task_begin_if0: {
1101 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1102 // *new_task);
1103 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1104 CGM.VoidPtrTy};
1105 llvm::FunctionType *FnTy =
1106 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1107 RTLFn =
1108 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1109 break;
1110 }
1111 case OMPRTL__kmpc_omp_task_complete_if0: {
1112 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1113 // *new_task);
1114 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1115 CGM.VoidPtrTy};
1116 llvm::FunctionType *FnTy =
1117 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1118 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1119 /*Name=*/"__kmpc_omp_task_complete_if0");
1120 break;
1121 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001122 case OMPRTL__kmpc_ordered: {
1123 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1124 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1125 llvm::FunctionType *FnTy =
1126 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1127 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1128 break;
1129 }
1130 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001131 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001132 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1133 llvm::FunctionType *FnTy =
1134 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1135 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1136 break;
1137 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001138 case OMPRTL__kmpc_omp_taskwait: {
1139 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1140 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1141 llvm::FunctionType *FnTy =
1142 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1143 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1144 break;
1145 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001146 case OMPRTL__kmpc_taskgroup: {
1147 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1148 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1149 llvm::FunctionType *FnTy =
1150 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1151 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1152 break;
1153 }
1154 case OMPRTL__kmpc_end_taskgroup: {
1155 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1156 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1157 llvm::FunctionType *FnTy =
1158 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1159 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1160 break;
1161 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001162 case OMPRTL__kmpc_push_proc_bind: {
1163 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1164 // int proc_bind)
1165 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1166 llvm::FunctionType *FnTy =
1167 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1168 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1169 break;
1170 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001171 case OMPRTL__kmpc_omp_task_with_deps: {
1172 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1173 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1174 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1175 llvm::Type *TypeParams[] = {
1176 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1177 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1178 llvm::FunctionType *FnTy =
1179 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1180 RTLFn =
1181 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1182 break;
1183 }
1184 case OMPRTL__kmpc_omp_wait_deps: {
1185 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1186 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1187 // kmp_depend_info_t *noalias_dep_list);
1188 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1189 CGM.Int32Ty, CGM.VoidPtrTy,
1190 CGM.Int32Ty, CGM.VoidPtrTy};
1191 llvm::FunctionType *FnTy =
1192 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1193 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1194 break;
1195 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001196 case OMPRTL__kmpc_cancellationpoint: {
1197 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1198 // global_tid, kmp_int32 cncl_kind)
1199 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1200 llvm::FunctionType *FnTy =
1201 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1202 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1203 break;
1204 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001205 case OMPRTL__kmpc_cancel: {
1206 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1207 // kmp_int32 cncl_kind)
1208 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1209 llvm::FunctionType *FnTy =
1210 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1211 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1212 break;
1213 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001214 case OMPRTL__kmpc_push_num_teams: {
1215 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1216 // kmp_int32 num_teams, kmp_int32 num_threads)
1217 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1218 CGM.Int32Ty};
1219 llvm::FunctionType *FnTy =
1220 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1221 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1222 break;
1223 }
1224 case OMPRTL__kmpc_fork_teams: {
1225 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1226 // microtask, ...);
1227 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1228 getKmpc_MicroPointerTy()};
1229 llvm::FunctionType *FnTy =
1230 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1231 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1232 break;
1233 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001234 case OMPRTL__tgt_target: {
1235 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1236 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1237 // *arg_types);
1238 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1239 CGM.VoidPtrTy,
1240 CGM.Int32Ty,
1241 CGM.VoidPtrPtrTy,
1242 CGM.VoidPtrPtrTy,
1243 CGM.SizeTy->getPointerTo(),
1244 CGM.Int32Ty->getPointerTo()};
1245 llvm::FunctionType *FnTy =
1246 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1247 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1248 break;
1249 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001250 case OMPRTL__tgt_target_teams: {
1251 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1252 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1253 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1254 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1255 CGM.VoidPtrTy,
1256 CGM.Int32Ty,
1257 CGM.VoidPtrPtrTy,
1258 CGM.VoidPtrPtrTy,
1259 CGM.SizeTy->getPointerTo(),
1260 CGM.Int32Ty->getPointerTo(),
1261 CGM.Int32Ty,
1262 CGM.Int32Ty};
1263 llvm::FunctionType *FnTy =
1264 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1265 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1266 break;
1267 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001268 case OMPRTL__tgt_register_lib: {
1269 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1270 QualType ParamTy =
1271 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1272 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1273 llvm::FunctionType *FnTy =
1274 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1275 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1276 break;
1277 }
1278 case OMPRTL__tgt_unregister_lib: {
1279 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1280 QualType ParamTy =
1281 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1282 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1283 llvm::FunctionType *FnTy =
1284 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1285 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1286 break;
1287 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001288 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001289 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001290 return RTLFn;
1291}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001292
Alexander Musman21212e42015-03-13 10:38:23 +00001293llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1294 bool IVSigned) {
1295 assert((IVSize == 32 || IVSize == 64) &&
1296 "IV size is not compatible with the omp runtime");
1297 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1298 : "__kmpc_for_static_init_4u")
1299 : (IVSigned ? "__kmpc_for_static_init_8"
1300 : "__kmpc_for_static_init_8u");
1301 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1302 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1303 llvm::Type *TypeParams[] = {
1304 getIdentTyPointerTy(), // loc
1305 CGM.Int32Ty, // tid
1306 CGM.Int32Ty, // schedtype
1307 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1308 PtrTy, // p_lower
1309 PtrTy, // p_upper
1310 PtrTy, // p_stride
1311 ITy, // incr
1312 ITy // chunk
1313 };
1314 llvm::FunctionType *FnTy =
1315 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1316 return CGM.CreateRuntimeFunction(FnTy, Name);
1317}
1318
Alexander Musman92bdaab2015-03-12 13:37:50 +00001319llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1320 bool IVSigned) {
1321 assert((IVSize == 32 || IVSize == 64) &&
1322 "IV size is not compatible with the omp runtime");
1323 auto Name =
1324 IVSize == 32
1325 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1326 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1327 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1328 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1329 CGM.Int32Ty, // tid
1330 CGM.Int32Ty, // schedtype
1331 ITy, // lower
1332 ITy, // upper
1333 ITy, // stride
1334 ITy // chunk
1335 };
1336 llvm::FunctionType *FnTy =
1337 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1338 return CGM.CreateRuntimeFunction(FnTy, Name);
1339}
1340
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001341llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1342 bool IVSigned) {
1343 assert((IVSize == 32 || IVSize == 64) &&
1344 "IV size is not compatible with the omp runtime");
1345 auto Name =
1346 IVSize == 32
1347 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1348 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1349 llvm::Type *TypeParams[] = {
1350 getIdentTyPointerTy(), // loc
1351 CGM.Int32Ty, // tid
1352 };
1353 llvm::FunctionType *FnTy =
1354 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1355 return CGM.CreateRuntimeFunction(FnTy, Name);
1356}
1357
Alexander Musman92bdaab2015-03-12 13:37:50 +00001358llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1359 bool IVSigned) {
1360 assert((IVSize == 32 || IVSize == 64) &&
1361 "IV size is not compatible with the omp runtime");
1362 auto Name =
1363 IVSize == 32
1364 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1365 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1366 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1367 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1368 llvm::Type *TypeParams[] = {
1369 getIdentTyPointerTy(), // loc
1370 CGM.Int32Ty, // tid
1371 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1372 PtrTy, // p_lower
1373 PtrTy, // p_upper
1374 PtrTy // p_stride
1375 };
1376 llvm::FunctionType *FnTy =
1377 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1378 return CGM.CreateRuntimeFunction(FnTy, Name);
1379}
1380
Alexey Bataev97720002014-11-11 04:05:39 +00001381llvm::Constant *
1382CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001383 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1384 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001385 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001386 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001387 Twine(CGM.getMangledName(VD)) + ".cache.");
1388}
1389
John McCall7f416cc2015-09-08 08:05:57 +00001390Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1391 const VarDecl *VD,
1392 Address VDAddr,
1393 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001394 if (CGM.getLangOpts().OpenMPUseTLS &&
1395 CGM.getContext().getTargetInfo().isTLSSupported())
1396 return VDAddr;
1397
John McCall7f416cc2015-09-08 08:05:57 +00001398 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001399 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001400 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1401 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001402 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1403 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001404 return Address(CGF.EmitRuntimeCall(
1405 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1406 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001407}
1408
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001409void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001410 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001411 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1412 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1413 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001414 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1415 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001416 OMPLoc);
1417 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1418 // to register constructor/destructor for variable.
1419 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001420 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1421 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001422 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001423 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001424 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001425}
1426
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001427llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001428 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001429 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001430 if (CGM.getLangOpts().OpenMPUseTLS &&
1431 CGM.getContext().getTargetInfo().isTLSSupported())
1432 return nullptr;
1433
Alexey Bataev97720002014-11-11 04:05:39 +00001434 VD = VD->getDefinition(CGM.getContext());
1435 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1436 ThreadPrivateWithDefinition.insert(VD);
1437 QualType ASTTy = VD->getType();
1438
1439 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1440 auto Init = VD->getAnyInitializer();
1441 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1442 // Generate function that re-emits the declaration's initializer into the
1443 // threadprivate copy of the variable VD
1444 CodeGenFunction CtorCGF(CGM);
1445 FunctionArgList Args;
1446 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1447 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1448 Args.push_back(&Dst);
1449
1450 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1451 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1452 /*isVariadic=*/false);
1453 auto FTy = CGM.getTypes().GetFunctionType(FI);
1454 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001455 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001456 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1457 Args, SourceLocation());
1458 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001459 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001460 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001461 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1462 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1463 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001464 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1465 /*IsInitializer=*/true);
1466 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001467 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001468 CGM.getContext().VoidPtrTy, Dst.getLocation());
1469 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1470 CtorCGF.FinishFunction();
1471 Ctor = Fn;
1472 }
1473 if (VD->getType().isDestructedType() != QualType::DK_none) {
1474 // Generate function that emits destructor call for the threadprivate copy
1475 // of the variable VD
1476 CodeGenFunction DtorCGF(CGM);
1477 FunctionArgList Args;
1478 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1479 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1480 Args.push_back(&Dst);
1481
1482 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1483 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1484 /*isVariadic=*/false);
1485 auto FTy = CGM.getTypes().GetFunctionType(FI);
1486 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001487 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001488 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1489 SourceLocation());
1490 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1491 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001492 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1493 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001494 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1495 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1496 DtorCGF.FinishFunction();
1497 Dtor = Fn;
1498 }
1499 // Do not emit init function if it is not required.
1500 if (!Ctor && !Dtor)
1501 return nullptr;
1502
1503 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1504 auto CopyCtorTy =
1505 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1506 /*isVarArg=*/false)->getPointerTo();
1507 // Copying constructor for the threadprivate variable.
1508 // Must be NULL - reserved by runtime, but currently it requires that this
1509 // parameter is always NULL. Otherwise it fires assertion.
1510 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1511 if (Ctor == nullptr) {
1512 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1513 /*isVarArg=*/false)->getPointerTo();
1514 Ctor = llvm::Constant::getNullValue(CtorTy);
1515 }
1516 if (Dtor == nullptr) {
1517 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1518 /*isVarArg=*/false)->getPointerTo();
1519 Dtor = llvm::Constant::getNullValue(DtorTy);
1520 }
1521 if (!CGF) {
1522 auto InitFunctionTy =
1523 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1524 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001525 InitFunctionTy, ".__omp_threadprivate_init_.",
1526 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001527 CodeGenFunction InitCGF(CGM);
1528 FunctionArgList ArgList;
1529 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1530 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1531 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001532 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001533 InitCGF.FinishFunction();
1534 return InitFunction;
1535 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001536 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001537 }
1538 return nullptr;
1539}
1540
Alexey Bataev1d677132015-04-22 13:57:31 +00001541/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1542/// function. Here is the logic:
1543/// if (Cond) {
1544/// ThenGen();
1545/// } else {
1546/// ElseGen();
1547/// }
1548static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1549 const RegionCodeGenTy &ThenGen,
1550 const RegionCodeGenTy &ElseGen) {
1551 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1552
1553 // If the condition constant folds and can be elided, try to avoid emitting
1554 // the condition and the dead arm of the if/else.
1555 bool CondConstant;
1556 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1557 CodeGenFunction::RunCleanupsScope Scope(CGF);
1558 if (CondConstant) {
1559 ThenGen(CGF);
1560 } else {
1561 ElseGen(CGF);
1562 }
1563 return;
1564 }
1565
1566 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1567 // emit the conditional branch.
1568 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1569 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1570 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1571 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1572
1573 // Emit the 'then' code.
1574 CGF.EmitBlock(ThenBlock);
1575 {
1576 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1577 ThenGen(CGF);
1578 }
1579 CGF.EmitBranch(ContBlock);
1580 // Emit the 'else' code if present.
1581 {
1582 // There is no need to emit line number for unconditional branch.
1583 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1584 CGF.EmitBlock(ElseBlock);
1585 }
1586 {
1587 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1588 ElseGen(CGF);
1589 }
1590 {
1591 // There is no need to emit line number for unconditional branch.
1592 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1593 CGF.EmitBranch(ContBlock);
1594 }
1595 // Emit the continuation block for code after the if.
1596 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001597}
1598
Alexey Bataev1d677132015-04-22 13:57:31 +00001599void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1600 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001601 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001602 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001603 if (!CGF.HaveInsertPoint())
1604 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001605 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001606 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1607 RTLoc](CodeGenFunction &CGF) {
1608 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1609 llvm::Value *Args[] = {
1610 RTLoc,
1611 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1612 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1613 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1614 RealArgs.append(std::begin(Args), std::end(Args));
1615 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1616
1617 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1618 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1619 };
1620 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1621 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001622 auto ThreadID = getThreadID(CGF, Loc);
1623 // Build calls:
1624 // __kmpc_serialized_parallel(&Loc, GTid);
1625 llvm::Value *Args[] = {RTLoc, ThreadID};
1626 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1627 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001628
Alexey Bataev1d677132015-04-22 13:57:31 +00001629 // OutlinedFn(&GTid, &zero, CapturedStruct);
1630 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001631 Address ZeroAddr =
1632 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1633 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001634 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001635 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1636 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1637 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1638 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001639 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001640
Alexey Bataev1d677132015-04-22 13:57:31 +00001641 // __kmpc_end_serialized_parallel(&Loc, GTid);
1642 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1643 CGF.EmitRuntimeCall(
1644 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1645 };
1646 if (IfCond) {
1647 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1648 } else {
1649 CodeGenFunction::RunCleanupsScope Scope(CGF);
1650 ThenGen(CGF);
1651 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001652}
1653
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001654// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001655// thread-ID variable (it is passed in a first argument of the outlined function
1656// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1657// regular serial code region, get thread ID by calling kmp_int32
1658// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1659// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001660Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1661 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001662 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001663 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001664 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001665 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001666
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001667 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001668 auto Int32Ty =
1669 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1670 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1671 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001672 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001673
1674 return ThreadIDTemp;
1675}
1676
Alexey Bataev97720002014-11-11 04:05:39 +00001677llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001678CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001679 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001680 SmallString<256> Buffer;
1681 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001682 Out << Name;
1683 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001684 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1685 if (Elem.second) {
1686 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001687 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001688 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001689 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001690
David Blaikie13156b62014-11-19 03:06:06 +00001691 return Elem.second = new llvm::GlobalVariable(
1692 CGM.getModule(), Ty, /*IsConstant*/ false,
1693 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1694 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001695}
1696
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001697llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001698 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001699 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001700}
1701
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001702namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001703template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001704 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001705 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001706
1707public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001708 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1709 : Callee(Callee) {
1710 assert(CleanupArgs.size() == N);
1711 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1712 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001713
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001714 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001715 if (!CGF.HaveInsertPoint())
1716 return;
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001717 CGF.EmitRuntimeCall(Callee, Args);
1718 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001719};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001720} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001721
1722void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1723 StringRef CriticalName,
1724 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001725 SourceLocation Loc, const Expr *Hint) {
1726 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001727 // CriticalOpGen();
1728 // __kmpc_end_critical(ident_t *, gtid, Lock);
1729 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001730 if (!CGF.HaveInsertPoint())
1731 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001732 CodeGenFunction::RunCleanupsScope Scope(CGF);
1733 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1734 getCriticalRegionLock(CriticalName)};
1735 if (Hint) {
1736 llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1737 std::end(Args));
1738 auto *HintVal = CGF.EmitScalarExpr(Hint);
1739 ArgsWithHint.push_back(
1740 CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1741 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1742 ArgsWithHint);
1743 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001744 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001745 // Build a call to __kmpc_end_critical
1746 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1747 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1748 llvm::makeArrayRef(Args));
1749 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001750}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001751
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001752static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001753 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001754 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001755 llvm::Value *CallBool = CGF.EmitScalarConversion(
1756 IfCond,
1757 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001758 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001759
1760 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1761 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1762 // Generate the branch (If-stmt)
1763 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1764 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001765 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001766 // Emit the rest of bblocks/branches
1767 CGF.EmitBranch(ContBlock);
1768 CGF.EmitBlock(ContBlock, true);
1769}
1770
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001771void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001772 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001773 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001774 if (!CGF.HaveInsertPoint())
1775 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001776 // if(__kmpc_master(ident_t *, gtid)) {
1777 // MasterOpGen();
1778 // __kmpc_end_master(ident_t *, gtid);
1779 // }
1780 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001781 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001782 auto *IsMaster =
1783 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001784 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1785 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001786 emitIfStmt(
1787 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1788 CodeGenFunction::RunCleanupsScope Scope(CGF);
1789 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1790 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1791 llvm::makeArrayRef(Args));
1792 MasterOpGen(CGF);
1793 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001794}
1795
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001796void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1797 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001798 if (!CGF.HaveInsertPoint())
1799 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001800 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1801 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001802 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001803 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001804 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001805}
1806
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001807void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1808 const RegionCodeGenTy &TaskgroupOpGen,
1809 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001810 if (!CGF.HaveInsertPoint())
1811 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001812 // __kmpc_taskgroup(ident_t *, gtid);
1813 // TaskgroupOpGen();
1814 // __kmpc_end_taskgroup(ident_t *, gtid);
1815 // Prepare arguments and build a call to __kmpc_taskgroup
1816 {
1817 CodeGenFunction::RunCleanupsScope Scope(CGF);
1818 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1819 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1820 // Build a call to __kmpc_end_taskgroup
1821 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1822 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1823 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001824 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001825 }
1826}
1827
John McCall7f416cc2015-09-08 08:05:57 +00001828/// Given an array of pointers to variables, project the address of a
1829/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001830static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1831 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001832 // Pull out the pointer to the variable.
1833 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001834 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001835 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1836
1837 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001838 Addr = CGF.Builder.CreateElementBitCast(
1839 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001840 return Addr;
1841}
1842
Alexey Bataeva63048e2015-03-23 06:18:07 +00001843static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001844 CodeGenModule &CGM, llvm::Type *ArgsType,
1845 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1846 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001847 auto &C = CGM.getContext();
1848 // void copy_func(void *LHSArg, void *RHSArg);
1849 FunctionArgList Args;
1850 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1851 C.VoidPtrTy);
1852 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1853 C.VoidPtrTy);
1854 Args.push_back(&LHSArg);
1855 Args.push_back(&RHSArg);
1856 FunctionType::ExtInfo EI;
1857 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1858 C.VoidTy, Args, EI, /*isVariadic=*/false);
1859 auto *Fn = llvm::Function::Create(
1860 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1861 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001862 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001863 CodeGenFunction CGF(CGM);
1864 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001865 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001866 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001867 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1868 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1869 ArgsType), CGF.getPointerAlign());
1870 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1871 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1872 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001873 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1874 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1875 // ...
1876 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001877 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001878 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1879 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1880
1881 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1882 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1883
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001884 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1885 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001886 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001887 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001888 CGF.FinishFunction();
1889 return Fn;
1890}
1891
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001892void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001893 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001894 SourceLocation Loc,
1895 ArrayRef<const Expr *> CopyprivateVars,
1896 ArrayRef<const Expr *> SrcExprs,
1897 ArrayRef<const Expr *> DstExprs,
1898 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001899 if (!CGF.HaveInsertPoint())
1900 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001901 assert(CopyprivateVars.size() == SrcExprs.size() &&
1902 CopyprivateVars.size() == DstExprs.size() &&
1903 CopyprivateVars.size() == AssignmentOps.size());
1904 auto &C = CGM.getContext();
1905 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001906 // if(__kmpc_single(ident_t *, gtid)) {
1907 // SingleOpGen();
1908 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001909 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001910 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001911 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1912 // <copy_func>, did_it);
1913
John McCall7f416cc2015-09-08 08:05:57 +00001914 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001915 if (!CopyprivateVars.empty()) {
1916 // int32 did_it = 0;
1917 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1918 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00001919 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001920 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001921 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001922 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001923 auto *IsSingle =
1924 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001925 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1926 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001927 emitIfStmt(
1928 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
1929 CodeGenFunction::RunCleanupsScope Scope(CGF);
1930 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
1931 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1932 llvm::makeArrayRef(Args));
1933 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001934 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001935 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00001936 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001937 }
1938 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001939 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1940 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00001941 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001942 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1943 auto CopyprivateArrayTy =
1944 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1945 /*IndexTypeQuals=*/0);
1946 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00001947 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001948 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1949 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001950 Address Elem = CGF.Builder.CreateConstArrayGEP(
1951 CopyprivateList, I, CGF.getPointerSize());
1952 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00001953 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001954 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
1955 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001956 }
1957 // Build function that copies private values from single region to all other
1958 // threads in the corresponding parallel region.
1959 auto *CpyFn = emitCopyprivateCopyFunction(
1960 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001961 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001962 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00001963 Address CL =
1964 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1965 CGF.VoidPtrTy);
1966 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001967 llvm::Value *Args[] = {
1968 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1969 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001970 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00001971 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001972 CpyFn, // void (*) (void *, void *) <copy_func>
1973 DidItVal // i32 did_it
1974 };
1975 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1976 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001977}
1978
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001979void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1980 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00001981 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001982 if (!CGF.HaveInsertPoint())
1983 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001984 // __kmpc_ordered(ident_t *, gtid);
1985 // OrderedOpGen();
1986 // __kmpc_end_ordered(ident_t *, gtid);
1987 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00001988 CodeGenFunction::RunCleanupsScope Scope(CGF);
1989 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001990 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1991 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1992 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001993 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001994 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1995 llvm::makeArrayRef(Args));
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001996 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00001997 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001998}
1999
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002000void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002001 OpenMPDirectiveKind Kind, bool EmitChecks,
2002 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002003 if (!CGF.HaveInsertPoint())
2004 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002005 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002006 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002007 unsigned Flags;
2008 if (Kind == OMPD_for)
2009 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2010 else if (Kind == OMPD_sections)
2011 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2012 else if (Kind == OMPD_single)
2013 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2014 else if (Kind == OMPD_barrier)
2015 Flags = OMP_IDENT_BARRIER_EXPL;
2016 else
2017 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002018 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2019 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002020 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2021 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002022 if (auto *OMPRegionInfo =
2023 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002024 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002025 auto *Result = CGF.EmitRuntimeCall(
2026 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002027 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002028 // if (__kmpc_cancel_barrier()) {
2029 // exit from construct;
2030 // }
2031 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2032 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2033 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2034 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2035 CGF.EmitBlock(ExitBB);
2036 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002037 auto CancelDestination =
2038 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002039 CGF.EmitBranchThroughCleanup(CancelDestination);
2040 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2041 }
2042 return;
2043 }
2044 }
2045 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002046}
2047
Alexander Musmanc6388682014-12-15 07:07:06 +00002048/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2049static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002050 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002051 switch (ScheduleKind) {
2052 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002053 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2054 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002055 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002056 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002057 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002058 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002059 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002060 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2061 case OMPC_SCHEDULE_auto:
2062 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002063 case OMPC_SCHEDULE_unknown:
2064 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002065 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002066 }
2067 llvm_unreachable("Unexpected runtime schedule");
2068}
2069
2070bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2071 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002072 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002073 return Schedule == OMP_sch_static;
2074}
2075
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002076bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002077 auto Schedule =
2078 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002079 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2080 return Schedule != OMP_sch_static;
2081}
2082
John McCall7f416cc2015-09-08 08:05:57 +00002083void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2084 SourceLocation Loc,
2085 OpenMPScheduleClauseKind ScheduleKind,
2086 unsigned IVSize, bool IVSigned,
2087 bool Ordered, llvm::Value *UB,
2088 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002089 if (!CGF.HaveInsertPoint())
2090 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002091 OpenMPSchedType Schedule =
2092 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002093 assert(Ordered ||
2094 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2095 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2096 // Call __kmpc_dispatch_init(
2097 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2098 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2099 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002100
John McCall7f416cc2015-09-08 08:05:57 +00002101 // If the Chunk was not specified in the clause - use default value 1.
2102 if (Chunk == nullptr)
2103 Chunk = CGF.Builder.getIntN(IVSize, 1);
2104 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002105 emitUpdateLocation(CGF, Loc),
2106 getThreadID(CGF, Loc),
2107 CGF.Builder.getInt32(Schedule), // Schedule type
2108 CGF.Builder.getIntN(IVSize, 0), // Lower
2109 UB, // Upper
2110 CGF.Builder.getIntN(IVSize, 1), // Stride
2111 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002112 };
2113 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2114}
2115
2116void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2117 SourceLocation Loc,
2118 OpenMPScheduleClauseKind ScheduleKind,
2119 unsigned IVSize, bool IVSigned,
2120 bool Ordered, Address IL, Address LB,
2121 Address UB, Address ST,
2122 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002123 if (!CGF.HaveInsertPoint())
2124 return;
John McCall7f416cc2015-09-08 08:05:57 +00002125 OpenMPSchedType Schedule =
2126 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
2127 assert(!Ordered);
2128 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2129 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked);
2130
2131 // Call __kmpc_for_static_init(
2132 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2133 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2134 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2135 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2136 if (Chunk == nullptr) {
2137 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
2138 "expected static non-chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00002139 // If the Chunk was not specified in the clause - use default value 1.
Alexander Musman92bdaab2015-03-12 13:37:50 +00002140 Chunk = CGF.Builder.getIntN(IVSize, 1);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002141 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002142 assert((Schedule == OMP_sch_static_chunked ||
2143 Schedule == OMP_ord_static_chunked) &&
2144 "expected static chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00002145 }
John McCall7f416cc2015-09-08 08:05:57 +00002146 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002147 emitUpdateLocation(CGF, Loc),
2148 getThreadID(CGF, Loc),
2149 CGF.Builder.getInt32(Schedule), // Schedule type
2150 IL.getPointer(), // &isLastIter
2151 LB.getPointer(), // &LB
2152 UB.getPointer(), // &UB
2153 ST.getPointer(), // &Stride
2154 CGF.Builder.getIntN(IVSize, 1), // Incr
2155 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002156 };
2157 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002158}
2159
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002160void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2161 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002162 if (!CGF.HaveInsertPoint())
2163 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002164 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002165 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002166 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2167 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002168}
2169
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002170void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2171 SourceLocation Loc,
2172 unsigned IVSize,
2173 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002174 if (!CGF.HaveInsertPoint())
2175 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002176 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002177 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002178 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2179}
2180
Alexander Musman92bdaab2015-03-12 13:37:50 +00002181llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2182 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002183 bool IVSigned, Address IL,
2184 Address LB, Address UB,
2185 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002186 // Call __kmpc_dispatch_next(
2187 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2188 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2189 // kmp_int[32|64] *p_stride);
2190 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002191 emitUpdateLocation(CGF, Loc),
2192 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002193 IL.getPointer(), // &isLastIter
2194 LB.getPointer(), // &Lower
2195 UB.getPointer(), // &Upper
2196 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002197 };
2198 llvm::Value *Call =
2199 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2200 return CGF.EmitScalarConversion(
2201 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002202 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002203}
2204
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002205void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2206 llvm::Value *NumThreads,
2207 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002208 if (!CGF.HaveInsertPoint())
2209 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002210 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2211 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002212 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002213 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002214 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2215 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002216}
2217
Alexey Bataev7f210c62015-06-18 13:40:03 +00002218void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2219 OpenMPProcBindClauseKind ProcBind,
2220 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002221 if (!CGF.HaveInsertPoint())
2222 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002223 // Constants for proc bind value accepted by the runtime.
2224 enum ProcBindTy {
2225 ProcBindFalse = 0,
2226 ProcBindTrue,
2227 ProcBindMaster,
2228 ProcBindClose,
2229 ProcBindSpread,
2230 ProcBindIntel,
2231 ProcBindDefault
2232 } RuntimeProcBind;
2233 switch (ProcBind) {
2234 case OMPC_PROC_BIND_master:
2235 RuntimeProcBind = ProcBindMaster;
2236 break;
2237 case OMPC_PROC_BIND_close:
2238 RuntimeProcBind = ProcBindClose;
2239 break;
2240 case OMPC_PROC_BIND_spread:
2241 RuntimeProcBind = ProcBindSpread;
2242 break;
2243 case OMPC_PROC_BIND_unknown:
2244 llvm_unreachable("Unsupported proc_bind value.");
2245 }
2246 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2247 llvm::Value *Args[] = {
2248 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2249 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2250 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2251}
2252
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002253void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2254 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002255 if (!CGF.HaveInsertPoint())
2256 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002257 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002258 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2259 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002260}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002261
Alexey Bataev62b63b12015-03-10 07:28:44 +00002262namespace {
2263/// \brief Indexes of fields for type kmp_task_t.
2264enum KmpTaskTFields {
2265 /// \brief List of shared variables.
2266 KmpTaskTShareds,
2267 /// \brief Task routine.
2268 KmpTaskTRoutine,
2269 /// \brief Partition id for the untied tasks.
2270 KmpTaskTPartId,
2271 /// \brief Function with call of destructors for private variables.
2272 KmpTaskTDestructors,
2273};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002274} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002275
Samuel Antaoee8fb302016-01-06 13:42:12 +00002276bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2277 // FIXME: Add other entries type when they become supported.
2278 return OffloadEntriesTargetRegion.empty();
2279}
2280
2281/// \brief Initialize target region entry.
2282void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2283 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2284 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002285 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002286 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2287 "only required for the device "
2288 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002289 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002290 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2291 ++OffloadingEntriesNum;
2292}
2293
2294void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2295 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2296 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002297 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002298 // If we are emitting code for a target, the entry is already initialized,
2299 // only has to be registered.
2300 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002301 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002302 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002303 auto &Entry =
2304 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002305 assert(Entry.isValid() && "Entry not initialized!");
2306 Entry.setAddress(Addr);
2307 Entry.setID(ID);
2308 return;
2309 } else {
2310 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002311 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002312 }
2313}
2314
2315bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002316 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2317 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002318 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2319 if (PerDevice == OffloadEntriesTargetRegion.end())
2320 return false;
2321 auto PerFile = PerDevice->second.find(FileID);
2322 if (PerFile == PerDevice->second.end())
2323 return false;
2324 auto PerParentName = PerFile->second.find(ParentName);
2325 if (PerParentName == PerFile->second.end())
2326 return false;
2327 auto PerLine = PerParentName->second.find(LineNum);
2328 if (PerLine == PerParentName->second.end())
2329 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002330 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002331 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002332 return false;
2333 return true;
2334}
2335
2336void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2337 const OffloadTargetRegionEntryInfoActTy &Action) {
2338 // Scan all target region entries and perform the provided action.
2339 for (auto &D : OffloadEntriesTargetRegion)
2340 for (auto &F : D.second)
2341 for (auto &P : F.second)
2342 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002343 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002344}
2345
2346/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2347/// \a Codegen. This is used to emit the two functions that register and
2348/// unregister the descriptor of the current compilation unit.
2349static llvm::Function *
2350createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2351 const RegionCodeGenTy &Codegen) {
2352 auto &C = CGM.getContext();
2353 FunctionArgList Args;
2354 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2355 /*Id=*/nullptr, C.VoidPtrTy);
2356 Args.push_back(&DummyPtr);
2357
2358 CodeGenFunction CGF(CGM);
2359 GlobalDecl();
2360 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2361 C.VoidTy, Args, FunctionType::ExtInfo(),
2362 /*isVariadic=*/false);
2363 auto FTy = CGM.getTypes().GetFunctionType(FI);
2364 auto *Fn =
2365 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2366 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2367 Codegen(CGF);
2368 CGF.FinishFunction();
2369 return Fn;
2370}
2371
2372llvm::Function *
2373CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2374
2375 // If we don't have entries or if we are emitting code for the device, we
2376 // don't need to do anything.
2377 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2378 return nullptr;
2379
2380 auto &M = CGM.getModule();
2381 auto &C = CGM.getContext();
2382
2383 // Get list of devices we care about
2384 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2385
2386 // We should be creating an offloading descriptor only if there are devices
2387 // specified.
2388 assert(!Devices.empty() && "No OpenMP offloading devices??");
2389
2390 // Create the external variables that will point to the begin and end of the
2391 // host entries section. These will be defined by the linker.
2392 auto *OffloadEntryTy =
2393 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2394 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2395 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002396 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002397 ".omp_offloading.entries_begin");
2398 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2399 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002400 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002401 ".omp_offloading.entries_end");
2402
2403 // Create all device images
2404 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2405 auto *DeviceImageTy = cast<llvm::StructType>(
2406 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2407
2408 for (unsigned i = 0; i < Devices.size(); ++i) {
2409 StringRef T = Devices[i].getTriple();
2410 auto *ImgBegin = new llvm::GlobalVariable(
2411 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002412 /*Initializer=*/nullptr,
2413 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002414 auto *ImgEnd = new llvm::GlobalVariable(
2415 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002416 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002417
2418 llvm::Constant *Dev =
2419 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2420 HostEntriesBegin, HostEntriesEnd, nullptr);
2421 DeviceImagesEntires.push_back(Dev);
2422 }
2423
2424 // Create device images global array.
2425 llvm::ArrayType *DeviceImagesInitTy =
2426 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2427 llvm::Constant *DeviceImagesInit =
2428 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2429
2430 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2431 M, DeviceImagesInitTy, /*isConstant=*/true,
2432 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2433 ".omp_offloading.device_images");
2434 DeviceImages->setUnnamedAddr(true);
2435
2436 // This is a Zero array to be used in the creation of the constant expressions
2437 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2438 llvm::Constant::getNullValue(CGM.Int32Ty)};
2439
2440 // Create the target region descriptor.
2441 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2442 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2443 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2444 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2445 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2446 Index),
2447 HostEntriesBegin, HostEntriesEnd, nullptr);
2448
2449 auto *Desc = new llvm::GlobalVariable(
2450 M, BinaryDescriptorTy, /*isConstant=*/true,
2451 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2452 ".omp_offloading.descriptor");
2453
2454 // Emit code to register or unregister the descriptor at execution
2455 // startup or closing, respectively.
2456
2457 // Create a variable to drive the registration and unregistration of the
2458 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2459 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2460 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2461 IdentInfo, C.CharTy);
2462
2463 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2464 CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2465 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2466 Desc);
2467 });
2468 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2469 CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2470 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2471 Desc);
2472 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2473 });
2474 return RegFn;
2475}
2476
Samuel Antao2de62b02016-02-13 23:35:10 +00002477void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2478 llvm::Constant *Addr, uint64_t Size) {
2479 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002480 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2481 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2482 llvm::LLVMContext &C = CGM.getModule().getContext();
2483 llvm::Module &M = CGM.getModule();
2484
2485 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002486 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002487
2488 // Create constant string with the name.
2489 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2490
2491 llvm::GlobalVariable *Str =
2492 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2493 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2494 ".omp_offloading.entry_name");
2495 Str->setUnnamedAddr(true);
2496 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2497
2498 // Create the entry struct.
2499 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2500 TgtOffloadEntryType, AddrPtr, StrPtr,
2501 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2502 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2503 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2504 EntryInit, ".omp_offloading.entry");
2505
2506 // The entry has to be created in the section the linker expects it to be.
2507 Entry->setSection(".omp_offloading.entries");
2508 // We can't have any padding between symbols, so we need to have 1-byte
2509 // alignment.
2510 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002511}
2512
2513void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2514 // Emit the offloading entries and metadata so that the device codegen side
2515 // can
2516 // easily figure out what to emit. The produced metadata looks like this:
2517 //
2518 // !omp_offload.info = !{!1, ...}
2519 //
2520 // Right now we only generate metadata for function that contain target
2521 // regions.
2522
2523 // If we do not have entries, we dont need to do anything.
2524 if (OffloadEntriesInfoManager.empty())
2525 return;
2526
2527 llvm::Module &M = CGM.getModule();
2528 llvm::LLVMContext &C = M.getContext();
2529 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2530 OrderedEntries(OffloadEntriesInfoManager.size());
2531
2532 // Create the offloading info metadata node.
2533 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2534
2535 // Auxiliar methods to create metadata values and strings.
2536 auto getMDInt = [&](unsigned v) {
2537 return llvm::ConstantAsMetadata::get(
2538 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2539 };
2540
2541 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2542
2543 // Create function that emits metadata for each target region entry;
2544 auto &&TargetRegionMetadataEmitter = [&](
2545 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002546 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2547 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2548 // Generate metadata for target regions. Each entry of this metadata
2549 // contains:
2550 // - Entry 0 -> Kind of this type of metadata (0).
2551 // - Entry 1 -> Device ID of the file where the entry was identified.
2552 // - Entry 2 -> File ID of the file where the entry was identified.
2553 // - Entry 3 -> Mangled name of the function where the entry was identified.
2554 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002555 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002556 // The first element of the metadata node is the kind.
2557 Ops.push_back(getMDInt(E.getKind()));
2558 Ops.push_back(getMDInt(DeviceID));
2559 Ops.push_back(getMDInt(FileID));
2560 Ops.push_back(getMDString(ParentName));
2561 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002562 Ops.push_back(getMDInt(E.getOrder()));
2563
2564 // Save this entry in the right position of the ordered entries array.
2565 OrderedEntries[E.getOrder()] = &E;
2566
2567 // Add metadata to the named metadata node.
2568 MD->addOperand(llvm::MDNode::get(C, Ops));
2569 };
2570
2571 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2572 TargetRegionMetadataEmitter);
2573
2574 for (auto *E : OrderedEntries) {
2575 assert(E && "All ordered entries must exist!");
2576 if (auto *CE =
2577 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2578 E)) {
2579 assert(CE->getID() && CE->getAddress() &&
2580 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002581 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002582 } else
2583 llvm_unreachable("Unsupported entry kind.");
2584 }
2585}
2586
2587/// \brief Loads all the offload entries information from the host IR
2588/// metadata.
2589void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2590 // If we are in target mode, load the metadata from the host IR. This code has
2591 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2592
2593 if (!CGM.getLangOpts().OpenMPIsDevice)
2594 return;
2595
2596 if (CGM.getLangOpts().OMPHostIRFile.empty())
2597 return;
2598
2599 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2600 if (Buf.getError())
2601 return;
2602
2603 llvm::LLVMContext C;
2604 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2605
2606 if (ME.getError())
2607 return;
2608
2609 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2610 if (!MD)
2611 return;
2612
2613 for (auto I : MD->operands()) {
2614 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2615
2616 auto getMDInt = [&](unsigned Idx) {
2617 llvm::ConstantAsMetadata *V =
2618 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2619 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2620 };
2621
2622 auto getMDString = [&](unsigned Idx) {
2623 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2624 return V->getString();
2625 };
2626
2627 switch (getMDInt(0)) {
2628 default:
2629 llvm_unreachable("Unexpected metadata!");
2630 break;
2631 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2632 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2633 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2634 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2635 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002636 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002637 break;
2638 }
2639 }
2640}
2641
Alexey Bataev62b63b12015-03-10 07:28:44 +00002642void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2643 if (!KmpRoutineEntryPtrTy) {
2644 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2645 auto &C = CGM.getContext();
2646 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2647 FunctionProtoType::ExtProtoInfo EPI;
2648 KmpRoutineEntryPtrQTy = C.getPointerType(
2649 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2650 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2651 }
2652}
2653
Alexey Bataevc71a4092015-09-11 10:29:41 +00002654static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2655 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002656 auto *Field = FieldDecl::Create(
2657 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2658 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2659 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2660 Field->setAccess(AS_public);
2661 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002662 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002663}
2664
Samuel Antaoee8fb302016-01-06 13:42:12 +00002665QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2666
2667 // Make sure the type of the entry is already created. This is the type we
2668 // have to create:
2669 // struct __tgt_offload_entry{
2670 // void *addr; // Pointer to the offload entry info.
2671 // // (function or global)
2672 // char *name; // Name of the function or global.
2673 // size_t size; // Size of the entry info (0 if it a function).
2674 // };
2675 if (TgtOffloadEntryQTy.isNull()) {
2676 ASTContext &C = CGM.getContext();
2677 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2678 RD->startDefinition();
2679 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2680 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2681 addFieldToRecordDecl(C, RD, C.getSizeType());
2682 RD->completeDefinition();
2683 TgtOffloadEntryQTy = C.getRecordType(RD);
2684 }
2685 return TgtOffloadEntryQTy;
2686}
2687
2688QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2689 // These are the types we need to build:
2690 // struct __tgt_device_image{
2691 // void *ImageStart; // Pointer to the target code start.
2692 // void *ImageEnd; // Pointer to the target code end.
2693 // // We also add the host entries to the device image, as it may be useful
2694 // // for the target runtime to have access to that information.
2695 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2696 // // the entries.
2697 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2698 // // entries (non inclusive).
2699 // };
2700 if (TgtDeviceImageQTy.isNull()) {
2701 ASTContext &C = CGM.getContext();
2702 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2703 RD->startDefinition();
2704 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2705 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2706 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2707 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2708 RD->completeDefinition();
2709 TgtDeviceImageQTy = C.getRecordType(RD);
2710 }
2711 return TgtDeviceImageQTy;
2712}
2713
2714QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2715 // struct __tgt_bin_desc{
2716 // int32_t NumDevices; // Number of devices supported.
2717 // __tgt_device_image *DeviceImages; // Arrays of device images
2718 // // (one per device).
2719 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2720 // // entries.
2721 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2722 // // entries (non inclusive).
2723 // };
2724 if (TgtBinaryDescriptorQTy.isNull()) {
2725 ASTContext &C = CGM.getContext();
2726 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2727 RD->startDefinition();
2728 addFieldToRecordDecl(
2729 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2730 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2731 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2732 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2733 RD->completeDefinition();
2734 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2735 }
2736 return TgtBinaryDescriptorQTy;
2737}
2738
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002739namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002740struct PrivateHelpersTy {
2741 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2742 const VarDecl *PrivateElemInit)
2743 : Original(Original), PrivateCopy(PrivateCopy),
2744 PrivateElemInit(PrivateElemInit) {}
2745 const VarDecl *Original;
2746 const VarDecl *PrivateCopy;
2747 const VarDecl *PrivateElemInit;
2748};
2749typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002750} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002751
Alexey Bataev9e034042015-05-05 04:05:12 +00002752static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002753createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002754 if (!Privates.empty()) {
2755 auto &C = CGM.getContext();
2756 // Build struct .kmp_privates_t. {
2757 // /* private vars */
2758 // };
2759 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2760 RD->startDefinition();
2761 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002762 auto *VD = Pair.second.Original;
2763 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002764 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002765 auto *FD = addFieldToRecordDecl(C, RD, Type);
2766 if (VD->hasAttrs()) {
2767 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2768 E(VD->getAttrs().end());
2769 I != E; ++I)
2770 FD->addAttr(*I);
2771 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002772 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002773 RD->completeDefinition();
2774 return RD;
2775 }
2776 return nullptr;
2777}
2778
Alexey Bataev9e034042015-05-05 04:05:12 +00002779static RecordDecl *
2780createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002781 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002782 auto &C = CGM.getContext();
2783 // Build struct kmp_task_t {
2784 // void * shareds;
2785 // kmp_routine_entry_t routine;
2786 // kmp_int32 part_id;
2787 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002788 // };
2789 auto *RD = C.buildImplicitRecord("kmp_task_t");
2790 RD->startDefinition();
2791 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2792 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2793 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2794 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002795 RD->completeDefinition();
2796 return RD;
2797}
2798
2799static RecordDecl *
2800createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002801 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002802 auto &C = CGM.getContext();
2803 // Build struct kmp_task_t_with_privates {
2804 // kmp_task_t task_data;
2805 // .kmp_privates_t. privates;
2806 // };
2807 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2808 RD->startDefinition();
2809 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002810 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2811 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2812 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002813 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002814 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002815}
2816
2817/// \brief Emit a proxy function which accepts kmp_task_t as the second
2818/// argument.
2819/// \code
2820/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002821/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2822/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002823/// return 0;
2824/// }
2825/// \endcode
2826static llvm::Value *
2827emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002828 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2829 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002830 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2831 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002832 auto &C = CGM.getContext();
2833 FunctionArgList Args;
2834 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2835 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002836 /*Id=*/nullptr,
2837 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002838 Args.push_back(&GtidArg);
2839 Args.push_back(&TaskTypeArg);
2840 FunctionType::ExtInfo Info;
2841 auto &TaskEntryFnInfo =
2842 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2843 /*isVariadic=*/false);
2844 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2845 auto *TaskEntry =
2846 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2847 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002848 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002849 CodeGenFunction CGF(CGM);
2850 CGF.disableDebugInfo();
2851 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2852
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002853 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2854 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002855 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002856 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002857 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2858 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2859 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002860 auto *KmpTaskTWithPrivatesQTyRD =
2861 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002862 LValue Base =
2863 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002864 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2865 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2866 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
2867 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
2868
2869 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
2870 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002871 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002872 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002873 CGF.ConvertTypeForMem(SharedsPtrTy));
2874
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002875 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
2876 llvm::Value *PrivatesParam;
2877 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
2878 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
2879 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002880 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002881 } else {
2882 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2883 }
2884
2885 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
2886 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002887 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2888 CGF.EmitStoreThroughLValue(
2889 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002890 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002891 CGF.FinishFunction();
2892 return TaskEntry;
2893}
2894
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002895static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2896 SourceLocation Loc,
2897 QualType KmpInt32Ty,
2898 QualType KmpTaskTWithPrivatesPtrQTy,
2899 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002900 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002901 FunctionArgList Args;
2902 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2903 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002904 /*Id=*/nullptr,
2905 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002906 Args.push_back(&GtidArg);
2907 Args.push_back(&TaskTypeArg);
2908 FunctionType::ExtInfo Info;
2909 auto &DestructorFnInfo =
2910 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2911 /*isVariadic=*/false);
2912 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2913 auto *DestructorFn =
2914 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2915 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002916 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
2917 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002918 CodeGenFunction CGF(CGM);
2919 CGF.disableDebugInfo();
2920 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
2921 Args);
2922
Alexey Bataev31300ed2016-02-04 11:27:03 +00002923 LValue Base = CGF.EmitLoadOfPointerLValue(
2924 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2925 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002926 auto *KmpTaskTWithPrivatesQTyRD =
2927 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2928 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002929 Base = CGF.EmitLValueForField(Base, *FI);
2930 for (auto *Field :
2931 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
2932 if (auto DtorKind = Field->getType().isDestructedType()) {
2933 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
2934 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
2935 }
2936 }
2937 CGF.FinishFunction();
2938 return DestructorFn;
2939}
2940
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002941/// \brief Emit a privates mapping function for correct handling of private and
2942/// firstprivate variables.
2943/// \code
2944/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
2945/// **noalias priv1,..., <tyn> **noalias privn) {
2946/// *priv1 = &.privates.priv1;
2947/// ...;
2948/// *privn = &.privates.privn;
2949/// }
2950/// \endcode
2951static llvm::Value *
2952emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00002953 ArrayRef<const Expr *> PrivateVars,
2954 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002955 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002956 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002957 auto &C = CGM.getContext();
2958 FunctionArgList Args;
2959 ImplicitParamDecl TaskPrivatesArg(
2960 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2961 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2962 Args.push_back(&TaskPrivatesArg);
2963 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2964 unsigned Counter = 1;
2965 for (auto *E: PrivateVars) {
2966 Args.push_back(ImplicitParamDecl::Create(
2967 C, /*DC=*/nullptr, Loc,
2968 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2969 .withConst()
2970 .withRestrict()));
2971 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2972 PrivateVarsPos[VD] = Counter;
2973 ++Counter;
2974 }
2975 for (auto *E : FirstprivateVars) {
2976 Args.push_back(ImplicitParamDecl::Create(
2977 C, /*DC=*/nullptr, Loc,
2978 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2979 .withConst()
2980 .withRestrict()));
2981 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2982 PrivateVarsPos[VD] = Counter;
2983 ++Counter;
2984 }
2985 FunctionType::ExtInfo Info;
2986 auto &TaskPrivatesMapFnInfo =
2987 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2988 /*isVariadic=*/false);
2989 auto *TaskPrivatesMapTy =
2990 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2991 auto *TaskPrivatesMap = llvm::Function::Create(
2992 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2993 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002994 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
2995 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00002996 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002997 CodeGenFunction CGF(CGM);
2998 CGF.disableDebugInfo();
2999 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3000 TaskPrivatesMapFnInfo, Args);
3001
3002 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003003 LValue Base = CGF.EmitLoadOfPointerLValue(
3004 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3005 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003006 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3007 Counter = 0;
3008 for (auto *Field : PrivatesQTyRD->fields()) {
3009 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3010 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003011 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003012 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3013 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003014 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003015 ++Counter;
3016 }
3017 CGF.FinishFunction();
3018 return TaskPrivatesMap;
3019}
3020
Alexey Bataev9e034042015-05-05 04:05:12 +00003021static int array_pod_sort_comparator(const PrivateDataTy *P1,
3022 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003023 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3024}
3025
3026void CGOpenMPRuntime::emitTaskCall(
3027 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3028 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00003029 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003030 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3031 ArrayRef<const Expr *> PrivateCopies,
3032 ArrayRef<const Expr *> FirstprivateVars,
3033 ArrayRef<const Expr *> FirstprivateCopies,
3034 ArrayRef<const Expr *> FirstprivateInits,
3035 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003036 if (!CGF.HaveInsertPoint())
3037 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003038 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00003039 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003040 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003041 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003042 for (auto *E : PrivateVars) {
3043 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3044 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003045 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003046 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3047 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003048 ++I;
3049 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003050 I = FirstprivateCopies.begin();
3051 auto IElemInitRef = FirstprivateInits.begin();
3052 for (auto *E : FirstprivateVars) {
3053 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3054 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003055 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003056 PrivateHelpersTy(
3057 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3058 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003059 ++I;
3060 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003061 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003062 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3063 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003064 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3065 // Build type kmp_routine_entry_t (if not built yet).
3066 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003067 // Build type kmp_task_t (if not built yet).
3068 if (KmpTaskTQTy.isNull()) {
3069 KmpTaskTQTy = C.getRecordType(
3070 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
3071 }
3072 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003073 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003074 auto *KmpTaskTWithPrivatesQTyRD =
3075 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3076 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3077 QualType KmpTaskTWithPrivatesPtrQTy =
3078 C.getPointerType(KmpTaskTWithPrivatesQTy);
3079 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3080 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003081 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003082 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3083
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003084 // Emit initial values for private copies (if any).
3085 llvm::Value *TaskPrivatesMap = nullptr;
3086 auto *TaskPrivatesMapTy =
3087 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3088 3)
3089 ->getType();
3090 if (!Privates.empty()) {
3091 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3092 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3093 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3094 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3095 TaskPrivatesMap, TaskPrivatesMapTy);
3096 } else {
3097 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3098 cast<llvm::PointerType>(TaskPrivatesMapTy));
3099 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003100 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3101 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003102 auto *TaskEntry = emitProxyTaskFunction(
3103 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003104 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003105
3106 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3107 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3108 // kmp_routine_entry_t *task_entry);
3109 // Task flags. Format is taken from
3110 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3111 // description of kmp_tasking_flags struct.
3112 const unsigned TiedFlag = 0x1;
3113 const unsigned FinalFlag = 0x2;
3114 unsigned Flags = Tied ? TiedFlag : 0;
3115 auto *TaskFlags =
3116 Final.getPointer()
3117 ? CGF.Builder.CreateSelect(Final.getPointer(),
3118 CGF.Builder.getInt32(FinalFlag),
3119 CGF.Builder.getInt32(/*C=*/0))
3120 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3121 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003122 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003123 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3124 getThreadID(CGF, Loc), TaskFlags,
3125 KmpTaskTWithPrivatesTySize, SharedsSize,
3126 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3127 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003128 auto *NewTask = CGF.EmitRuntimeCall(
3129 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003130 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3131 NewTask, KmpTaskTWithPrivatesPtrTy);
3132 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3133 KmpTaskTWithPrivatesQTy);
3134 LValue TDBase =
3135 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003136 // Fill the data in the resulting kmp_task_t record.
3137 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003138 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003139 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003140 KmpTaskSharedsPtr =
3141 Address(CGF.EmitLoadOfScalar(
3142 CGF.EmitLValueForField(
3143 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3144 KmpTaskTShareds)),
3145 Loc),
3146 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003147 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003148 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003149 // Emit initial values for private copies (if any).
3150 bool NeedsCleanup = false;
3151 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003152 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3153 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003154 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003155 LValue SharedsBase;
3156 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003157 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003158 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3159 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3160 SharedsTy);
3161 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003162 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3163 cast<CapturedStmt>(*D.getAssociatedStmt()));
3164 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003165 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003166 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003167 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003168 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003169 if (auto *Elem = Pair.second.PrivateElemInit) {
3170 auto *OriginalVD = Pair.second.Original;
3171 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3172 auto SharedRefLValue =
3173 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003174 SharedRefLValue = CGF.MakeAddrLValue(
3175 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3176 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003177 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003178 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003179 // Initialize firstprivate array.
3180 if (!isa<CXXConstructExpr>(Init) ||
3181 CGF.isTrivialInitializer(Init)) {
3182 // Perform simple memcpy.
3183 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003184 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003185 } else {
3186 // Initialize firstprivate array using element-by-element
3187 // intialization.
3188 CGF.EmitOMPAggregateAssign(
3189 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003190 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003191 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003192 // Clean up any temporaries needed by the initialization.
3193 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003194 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003195 return SrcElement;
3196 });
3197 (void)InitScope.Privatize();
3198 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003199 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3200 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003201 CGF.EmitAnyExprToMem(Init, DestElement,
3202 Init->getType().getQualifiers(),
3203 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003204 });
3205 }
3206 } else {
3207 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003208 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003209 return SharedRefLValue.getAddress();
3210 });
3211 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003212 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003213 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3214 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003215 }
3216 } else {
3217 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3218 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003219 }
3220 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003221 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003222 }
3223 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003224 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003225 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003226 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3227 KmpTaskTWithPrivatesPtrQTy,
3228 KmpTaskTWithPrivatesQTy)
3229 : llvm::ConstantPointerNull::get(
3230 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3231 LValue Destructor = CGF.EmitLValueForField(
3232 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3233 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3234 DestructorFn, KmpRoutineEntryPtrTy),
3235 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003236
3237 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003238 Address DependenciesArray = Address::invalid();
3239 unsigned NumDependencies = Dependences.size();
3240 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003241 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003242 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003243 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3244 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003245 QualType FlagsTy =
3246 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003247 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3248 if (KmpDependInfoTy.isNull()) {
3249 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3250 KmpDependInfoRD->startDefinition();
3251 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3252 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3253 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3254 KmpDependInfoRD->completeDefinition();
3255 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3256 } else {
3257 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3258 }
John McCall7f416cc2015-09-08 08:05:57 +00003259 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003260 // Define type kmp_depend_info[<Dependences.size()>];
3261 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003262 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003263 ArrayType::Normal, /*IndexTypeQuals=*/0);
3264 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00003265 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
3266 for (unsigned i = 0; i < NumDependencies; ++i) {
3267 const Expr *E = Dependences[i].second;
3268 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003269 llvm::Value *Size;
3270 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003271 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3272 LValue UpAddrLVal =
3273 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3274 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003275 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003276 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003277 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003278 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3279 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003280 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003281 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003282 auto Base = CGF.MakeAddrLValue(
3283 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003284 KmpDependInfoTy);
3285 // deps[i].base_addr = &<Dependences[i].second>;
3286 auto BaseAddrLVal = CGF.EmitLValueForField(
3287 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003288 CGF.EmitStoreOfScalar(
3289 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3290 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003291 // deps[i].len = sizeof(<Dependences[i].second>);
3292 auto LenLVal = CGF.EmitLValueForField(
3293 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3294 CGF.EmitStoreOfScalar(Size, LenLVal);
3295 // deps[i].flags = <Dependences[i].first>;
3296 RTLDependenceKindTy DepKind;
3297 switch (Dependences[i].first) {
3298 case OMPC_DEPEND_in:
3299 DepKind = DepIn;
3300 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003301 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003302 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003303 case OMPC_DEPEND_inout:
3304 DepKind = DepInOut;
3305 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003306 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003307 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003308 case OMPC_DEPEND_unknown:
3309 llvm_unreachable("Unknown task dependence type");
3310 }
3311 auto FlagsLVal = CGF.EmitLValueForField(
3312 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3313 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3314 FlagsLVal);
3315 }
John McCall7f416cc2015-09-08 08:05:57 +00003316 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3317 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003318 CGF.VoidPtrTy);
3319 }
3320
Alexey Bataev62b63b12015-03-10 07:28:44 +00003321 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3322 // libcall.
3323 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3324 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003325 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3326 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3327 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3328 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003329 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003330 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003331 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3332 llvm::Value *DepTaskArgs[7];
3333 if (NumDependencies) {
3334 DepTaskArgs[0] = UpLoc;
3335 DepTaskArgs[1] = ThreadID;
3336 DepTaskArgs[2] = NewTask;
3337 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3338 DepTaskArgs[4] = DependenciesArray.getPointer();
3339 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3340 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3341 }
3342 auto &&ThenCodeGen = [this, NumDependencies,
3343 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3344 // TODO: add check for untied tasks.
3345 if (NumDependencies) {
3346 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3347 DepTaskArgs);
3348 } else {
3349 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3350 TaskArgs);
3351 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003352 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003353 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3354 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00003355
3356 llvm::Value *DepWaitTaskArgs[6];
3357 if (NumDependencies) {
3358 DepWaitTaskArgs[0] = UpLoc;
3359 DepWaitTaskArgs[1] = ThreadID;
3360 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3361 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3362 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3363 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3364 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003365 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00003366 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003367 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3368 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3369 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3370 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3371 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003372 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003373 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3374 DepWaitTaskArgs);
3375 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3376 // kmp_task_t *new_task);
3377 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3378 TaskArgs);
3379 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3380 // kmp_task_t *new_task);
3381 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3382 NormalAndEHCleanup,
3383 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3384 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00003385
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003386 // Call proxy_task_entry(gtid, new_task);
3387 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3388 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3389 };
John McCall7f416cc2015-09-08 08:05:57 +00003390
Alexey Bataev1d677132015-04-22 13:57:31 +00003391 if (IfCond) {
3392 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3393 } else {
3394 CodeGenFunction::RunCleanupsScope Scope(CGF);
3395 ThenCodeGen(CGF);
3396 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003397}
3398
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003399/// \brief Emit reduction operation for each element of array (required for
3400/// array sections) LHS op = RHS.
3401/// \param Type Type of array.
3402/// \param LHSVar Variable on the left side of the reduction operation
3403/// (references element of array in original variable).
3404/// \param RHSVar Variable on the right side of the reduction operation
3405/// (references element of array in original variable).
3406/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3407/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003408static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003409 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3410 const VarDecl *RHSVar,
3411 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3412 const Expr *, const Expr *)> &RedOpGen,
3413 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3414 const Expr *UpExpr = nullptr) {
3415 // Perform element-by-element initialization.
3416 QualType ElementTy;
3417 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3418 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3419
3420 // Drill down to the base element type on both arrays.
3421 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3422 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3423
3424 auto RHSBegin = RHSAddr.getPointer();
3425 auto LHSBegin = LHSAddr.getPointer();
3426 // Cast from pointer to array type to pointer to single element.
3427 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3428 // The basic structure here is a while-do loop.
3429 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3430 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3431 auto IsEmpty =
3432 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3433 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3434
3435 // Enter the loop body, making that address the current address.
3436 auto EntryBB = CGF.Builder.GetInsertBlock();
3437 CGF.EmitBlock(BodyBB);
3438
3439 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3440
3441 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3442 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3443 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3444 Address RHSElementCurrent =
3445 Address(RHSElementPHI,
3446 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3447
3448 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3449 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3450 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3451 Address LHSElementCurrent =
3452 Address(LHSElementPHI,
3453 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3454
3455 // Emit copy.
3456 CodeGenFunction::OMPPrivateScope Scope(CGF);
3457 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3458 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3459 Scope.Privatize();
3460 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3461 Scope.ForceCleanup();
3462
3463 // Shift the address forward by one element.
3464 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3465 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3466 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3467 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3468 // Check whether we've reached the end.
3469 auto Done =
3470 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3471 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3472 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3473 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3474
3475 // Done.
3476 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3477}
3478
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003479static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3480 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003481 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003482 ArrayRef<const Expr *> LHSExprs,
3483 ArrayRef<const Expr *> RHSExprs,
3484 ArrayRef<const Expr *> ReductionOps) {
3485 auto &C = CGM.getContext();
3486
3487 // void reduction_func(void *LHSArg, void *RHSArg);
3488 FunctionArgList Args;
3489 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3490 C.VoidPtrTy);
3491 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3492 C.VoidPtrTy);
3493 Args.push_back(&LHSArg);
3494 Args.push_back(&RHSArg);
3495 FunctionType::ExtInfo EI;
3496 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3497 C.VoidTy, Args, EI, /*isVariadic=*/false);
3498 auto *Fn = llvm::Function::Create(
3499 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3500 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003501 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003502 CodeGenFunction CGF(CGM);
3503 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3504
3505 // Dst = (void*[n])(LHSArg);
3506 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003507 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3508 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3509 ArgsType), CGF.getPointerAlign());
3510 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3511 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3512 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003513
3514 // ...
3515 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3516 // ...
3517 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003518 auto IPriv = Privates.begin();
3519 unsigned Idx = 0;
3520 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003521 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3522 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003523 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003524 });
3525 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3526 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003527 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003528 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003529 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003530 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003531 // Get array size and emit VLA type.
3532 ++Idx;
3533 Address Elem =
3534 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3535 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003536 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3537 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003538 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003539 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003540 CGF.EmitVariablyModifiedType(PrivTy);
3541 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003542 }
3543 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003544 IPriv = Privates.begin();
3545 auto ILHS = LHSExprs.begin();
3546 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003547 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003548 if ((*IPriv)->getType()->isArrayType()) {
3549 // Emit reduction for array section.
3550 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3551 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3552 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3553 [=](CodeGenFunction &CGF, const Expr *,
3554 const Expr *,
3555 const Expr *) { CGF.EmitIgnoredExpr(E); });
3556 } else
3557 // Emit reduction for array subscript or single variable.
3558 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003559 ++IPriv;
3560 ++ILHS;
3561 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003562 }
3563 Scope.ForceCleanup();
3564 CGF.FinishFunction();
3565 return Fn;
3566}
3567
3568void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003569 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003570 ArrayRef<const Expr *> LHSExprs,
3571 ArrayRef<const Expr *> RHSExprs,
3572 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003573 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003574 if (!CGF.HaveInsertPoint())
3575 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003576 // Next code should be emitted for reduction:
3577 //
3578 // static kmp_critical_name lock = { 0 };
3579 //
3580 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3581 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3582 // ...
3583 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3584 // *(Type<n>-1*)rhs[<n>-1]);
3585 // }
3586 //
3587 // ...
3588 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3589 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3590 // RedList, reduce_func, &<lock>)) {
3591 // case 1:
3592 // ...
3593 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3594 // ...
3595 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3596 // break;
3597 // case 2:
3598 // ...
3599 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3600 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003601 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003602 // break;
3603 // default:;
3604 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003605 //
3606 // if SimpleReduction is true, only the next code is generated:
3607 // ...
3608 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3609 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003610
3611 auto &C = CGM.getContext();
3612
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003613 if (SimpleReduction) {
3614 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003615 auto IPriv = Privates.begin();
3616 auto ILHS = LHSExprs.begin();
3617 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003618 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003619 if ((*IPriv)->getType()->isArrayType()) {
3620 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3621 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3622 EmitOMPAggregateReduction(
3623 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3624 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3625 const Expr *) { CGF.EmitIgnoredExpr(E); });
3626 } else
3627 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003628 ++IPriv;
3629 ++ILHS;
3630 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003631 }
3632 return;
3633 }
3634
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003635 // 1. Build a list of reduction variables.
3636 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003637 auto Size = RHSExprs.size();
3638 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003639 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003640 // Reserve place for array size.
3641 ++Size;
3642 }
3643 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003644 QualType ReductionArrayTy =
3645 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3646 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003647 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003648 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003649 auto IPriv = Privates.begin();
3650 unsigned Idx = 0;
3651 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003652 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003653 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003654 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003655 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003656 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3657 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003658 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003659 // Store array size.
3660 ++Idx;
3661 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3662 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003663 llvm::Value *Size = CGF.Builder.CreateIntCast(
3664 CGF.getVLASize(
3665 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3666 .first,
3667 CGF.SizeTy, /*isSigned=*/false);
3668 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3669 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003670 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003671 }
3672
3673 // 2. Emit reduce_func().
3674 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003675 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3676 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003677
3678 // 3. Create static kmp_critical_name lock = { 0 };
3679 auto *Lock = getCriticalRegionLock(".reduction");
3680
3681 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3682 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003683 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003684 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003685 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003686 auto *RL =
3687 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3688 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003689 llvm::Value *Args[] = {
3690 IdentTLoc, // ident_t *<loc>
3691 ThreadId, // i32 <gtid>
3692 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3693 ReductionArrayTySize, // size_type sizeof(RedList)
3694 RL, // void *RedList
3695 ReductionFn, // void (*) (void *, void *) <reduce_func>
3696 Lock // kmp_critical_name *&<lock>
3697 };
3698 auto Res = CGF.EmitRuntimeCall(
3699 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3700 : OMPRTL__kmpc_reduce),
3701 Args);
3702
3703 // 5. Build switch(res)
3704 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3705 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3706
3707 // 6. Build case 1:
3708 // ...
3709 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3710 // ...
3711 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3712 // break;
3713 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3714 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3715 CGF.EmitBlock(Case1BB);
3716
3717 {
3718 CodeGenFunction::RunCleanupsScope Scope(CGF);
3719 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3720 llvm::Value *EndArgs[] = {
3721 IdentTLoc, // ident_t *<loc>
3722 ThreadId, // i32 <gtid>
3723 Lock // kmp_critical_name *&<lock>
3724 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003725 CGF.EHStack
3726 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3727 NormalAndEHCleanup,
3728 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3729 : OMPRTL__kmpc_end_reduce),
3730 llvm::makeArrayRef(EndArgs));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003731 auto IPriv = Privates.begin();
3732 auto ILHS = LHSExprs.begin();
3733 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003734 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003735 if ((*IPriv)->getType()->isArrayType()) {
3736 // Emit reduction for array section.
3737 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3738 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3739 EmitOMPAggregateReduction(
3740 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3741 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3742 const Expr *) { CGF.EmitIgnoredExpr(E); });
3743 } else
3744 // Emit reduction for array subscript or single variable.
3745 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003746 ++IPriv;
3747 ++ILHS;
3748 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003749 }
3750 }
3751
3752 CGF.EmitBranch(DefaultBB);
3753
3754 // 7. Build case 2:
3755 // ...
3756 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3757 // ...
3758 // break;
3759 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3760 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3761 CGF.EmitBlock(Case2BB);
3762
3763 {
3764 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00003765 if (!WithNowait) {
3766 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3767 llvm::Value *EndArgs[] = {
3768 IdentTLoc, // ident_t *<loc>
3769 ThreadId, // i32 <gtid>
3770 Lock // kmp_critical_name *&<lock>
3771 };
3772 CGF.EHStack
3773 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3774 NormalAndEHCleanup,
3775 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3776 llvm::makeArrayRef(EndArgs));
3777 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003778 auto ILHS = LHSExprs.begin();
3779 auto IRHS = RHSExprs.begin();
3780 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003781 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003782 const Expr *XExpr = nullptr;
3783 const Expr *EExpr = nullptr;
3784 const Expr *UpExpr = nullptr;
3785 BinaryOperatorKind BO = BO_Comma;
3786 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3787 if (BO->getOpcode() == BO_Assign) {
3788 XExpr = BO->getLHS();
3789 UpExpr = BO->getRHS();
3790 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003791 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003792 // Try to emit update expression as a simple atomic.
3793 auto *RHSExpr = UpExpr;
3794 if (RHSExpr) {
3795 // Analyze RHS part of the whole expression.
3796 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3797 RHSExpr->IgnoreParenImpCasts())) {
3798 // If this is a conditional operator, analyze its condition for
3799 // min/max reduction operator.
3800 RHSExpr = ACO->getCond();
3801 }
3802 if (auto *BORHS =
3803 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3804 EExpr = BORHS->getRHS();
3805 BO = BORHS->getOpcode();
3806 }
Alexey Bataev69a47792015-05-07 03:54:03 +00003807 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003808 if (XExpr) {
3809 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3810 auto &&AtomicRedGen = [this, BO, VD, IPriv,
3811 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3812 const Expr *EExpr, const Expr *UpExpr) {
3813 LValue X = CGF.EmitLValue(XExpr);
3814 RValue E;
3815 if (EExpr)
3816 E = CGF.EmitAnyExpr(EExpr);
3817 CGF.EmitOMPAtomicSimpleUpdateExpr(
3818 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
Alexey Bataev8524d152016-01-21 12:35:58 +00003819 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003820 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev8524d152016-01-21 12:35:58 +00003821 PrivateScope.addPrivate(
3822 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3823 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3824 CGF.emitOMPSimpleStore(
3825 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3826 VD->getType().getNonReferenceType(), Loc);
3827 return LHSTemp;
3828 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003829 (void)PrivateScope.Privatize();
3830 return CGF.EmitAnyExpr(UpExpr);
3831 });
3832 };
3833 if ((*IPriv)->getType()->isArrayType()) {
3834 // Emit atomic reduction for array section.
3835 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3836 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3837 AtomicRedGen, XExpr, EExpr, UpExpr);
3838 } else
3839 // Emit atomic reduction for array subscript or single variable.
3840 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3841 } else {
3842 // Emit as a critical region.
3843 auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3844 const Expr *, const Expr *) {
3845 emitCriticalRegion(
3846 CGF, ".atomic_reduction",
3847 [E](CodeGenFunction &CGF) { CGF.EmitIgnoredExpr(E); }, Loc);
3848 };
3849 if ((*IPriv)->getType()->isArrayType()) {
3850 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3851 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3852 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3853 CritRedGen);
3854 } else
3855 CritRedGen(CGF, nullptr, nullptr, nullptr);
3856 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003857 ++ILHS;
3858 ++IRHS;
3859 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003860 }
3861 }
3862
3863 CGF.EmitBranch(DefaultBB);
3864 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3865}
3866
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003867void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
3868 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003869 if (!CGF.HaveInsertPoint())
3870 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003871 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
3872 // global_tid);
3873 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3874 // Ignore return result until untied tasks are supported.
3875 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
3876}
3877
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003878void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003879 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003880 const RegionCodeGenTy &CodeGen,
3881 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003882 if (!CGF.HaveInsertPoint())
3883 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003884 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003885 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00003886}
3887
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003888namespace {
3889enum RTCancelKind {
3890 CancelNoreq = 0,
3891 CancelParallel = 1,
3892 CancelLoop = 2,
3893 CancelSections = 3,
3894 CancelTaskgroup = 4
3895};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003896} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003897
3898static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
3899 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00003900 if (CancelRegion == OMPD_parallel)
3901 CancelKind = CancelParallel;
3902 else if (CancelRegion == OMPD_for)
3903 CancelKind = CancelLoop;
3904 else if (CancelRegion == OMPD_sections)
3905 CancelKind = CancelSections;
3906 else {
3907 assert(CancelRegion == OMPD_taskgroup);
3908 CancelKind = CancelTaskgroup;
3909 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003910 return CancelKind;
3911}
3912
3913void CGOpenMPRuntime::emitCancellationPointCall(
3914 CodeGenFunction &CGF, SourceLocation Loc,
3915 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003916 if (!CGF.HaveInsertPoint())
3917 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003918 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
3919 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003920 if (auto *OMPRegionInfo =
3921 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003922 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003923 llvm::Value *Args[] = {
3924 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3925 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003926 // Ignore return result until untied tasks are supported.
3927 auto *Result = CGF.EmitRuntimeCall(
3928 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
3929 // if (__kmpc_cancellationpoint()) {
3930 // __kmpc_cancel_barrier();
3931 // exit from construct;
3932 // }
3933 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3934 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3935 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3936 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3937 CGF.EmitBlock(ExitBB);
3938 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003939 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003940 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003941 auto CancelDest =
3942 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003943 CGF.EmitBranchThroughCleanup(CancelDest);
3944 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3945 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003946 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003947}
3948
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003949void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00003950 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003951 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003952 if (!CGF.HaveInsertPoint())
3953 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003954 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
3955 // kmp_int32 cncl_kind);
3956 if (auto *OMPRegionInfo =
3957 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003958 auto &&ThenGen = [this, Loc, CancelRegion,
3959 OMPRegionInfo](CodeGenFunction &CGF) {
3960 llvm::Value *Args[] = {
3961 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3962 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
3963 // Ignore return result until untied tasks are supported.
3964 auto *Result =
3965 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
3966 // if (__kmpc_cancel()) {
3967 // __kmpc_cancel_barrier();
3968 // exit from construct;
3969 // }
3970 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3971 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3972 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3973 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3974 CGF.EmitBlock(ExitBB);
3975 // __kmpc_cancel_barrier();
3976 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
3977 // exit from construct;
3978 auto CancelDest =
3979 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3980 CGF.EmitBranchThroughCleanup(CancelDest);
3981 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3982 };
3983 if (IfCond)
3984 emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
3985 else
3986 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003987 }
3988}
Samuel Antaobed3c462015-10-02 16:14:20 +00003989
Samuel Antaoee8fb302016-01-06 13:42:12 +00003990/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00003991/// consists of the file and device IDs as well as line number associated with
3992/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003993static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
3994 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00003995 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003996
3997 auto &SM = C.getSourceManager();
3998
3999 // The loc should be always valid and have a file ID (the user cannot use
4000 // #pragma directives in macros)
4001
4002 assert(Loc.isValid() && "Source location is expected to be always valid.");
4003 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4004
4005 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4006 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4007
4008 llvm::sys::fs::UniqueID ID;
4009 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4010 llvm_unreachable("Source file with target region no longer exists!");
4011
4012 DeviceID = ID.getDevice();
4013 FileID = ID.getFile();
4014 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004015}
4016
4017void CGOpenMPRuntime::emitTargetOutlinedFunction(
4018 const OMPExecutableDirective &D, StringRef ParentName,
4019 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4020 bool IsOffloadEntry) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004021 assert(!ParentName.empty() && "Invalid target region parent name!");
4022
Samuel Antaobed3c462015-10-02 16:14:20 +00004023 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4024
Samuel Antaoee8fb302016-01-06 13:42:12 +00004025 // Emit target region as a standalone region.
4026 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
4027 CGF.EmitStmt(CS.getCapturedStmt());
4028 };
4029
Samuel Antao2de62b02016-02-13 23:35:10 +00004030 // Create a unique name for the entry function using the source location
4031 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004032 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004033 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004034 //
4035 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004036 // mangled name of the function that encloses the target region and BB is the
4037 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004038
4039 unsigned DeviceID;
4040 unsigned FileID;
4041 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004042 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004043 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004044 SmallString<64> EntryFnName;
4045 {
4046 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004047 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4048 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004049 }
4050
Samuel Antaobed3c462015-10-02 16:14:20 +00004051 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004052 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004053 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004054
4055 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4056
4057 // If this target outline function is not an offload entry, we don't need to
4058 // register it.
4059 if (!IsOffloadEntry)
4060 return;
4061
4062 // The target region ID is used by the runtime library to identify the current
4063 // target region, so it only has to be unique and not necessarily point to
4064 // anything. It could be the pointer to the outlined function that implements
4065 // the target region, but we aren't using that so that the compiler doesn't
4066 // need to keep that, and could therefore inline the host function if proven
4067 // worthwhile during optimization. In the other hand, if emitting code for the
4068 // device, the ID has to be the function address so that it can retrieved from
4069 // the offloading entry and launched by the runtime library. We also mark the
4070 // outlined function to have external linkage in case we are emitting code for
4071 // the device, because these functions will be entry points to the device.
4072
4073 if (CGM.getLangOpts().OpenMPIsDevice) {
4074 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4075 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4076 } else
4077 OutlinedFnID = new llvm::GlobalVariable(
4078 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4079 llvm::GlobalValue::PrivateLinkage,
4080 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4081
4082 // Register the information for the entry associated with this target region.
4083 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004084 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004085}
4086
Samuel Antaob68e2db2016-03-03 16:20:23 +00004087/// \brief Emit the num_teams clause of an enclosed teams directive at the
4088/// target region scope. If there is no teams directive associated with the
4089/// target directive, or if there is no num_teams clause associated with the
4090/// enclosed teams directive, return nullptr.
4091static llvm::Value *
4092emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4093 CodeGenFunction &CGF,
4094 const OMPExecutableDirective &D) {
4095
4096 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4097 "teams directive expected to be "
4098 "emitted only for the host!");
4099
4100 // FIXME: For the moment we do not support combined directives with target and
4101 // teams, so we do not expect to get any num_teams clause in the provided
4102 // directive. Once we support that, this assertion can be replaced by the
4103 // actual emission of the clause expression.
4104 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4105 "Not expecting clause in directive.");
4106
4107 // If the current target region has a teams region enclosed, we need to get
4108 // the number of teams to pass to the runtime function call. This is done
4109 // by generating the expression in a inlined region. This is required because
4110 // the expression is captured in the enclosing target environment when the
4111 // teams directive is not combined with target.
4112
4113 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4114
4115 // FIXME: Accommodate other combined directives with teams when they become
4116 // available.
4117 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4118 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4119 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4120 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4121 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4122 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4123 /*IsSigned=*/true);
4124 }
4125
4126 // If we have an enclosed teams directive but no num_teams clause we use
4127 // the default value 0.
4128 return CGF.Builder.getInt32(0);
4129 }
4130
4131 // No teams associated with the directive.
4132 return nullptr;
4133}
4134
4135/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4136/// target region scope. If there is no teams directive associated with the
4137/// target directive, or if there is no thread_limit clause associated with the
4138/// enclosed teams directive, return nullptr.
4139static llvm::Value *
4140emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4141 CodeGenFunction &CGF,
4142 const OMPExecutableDirective &D) {
4143
4144 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4145 "teams directive expected to be "
4146 "emitted only for the host!");
4147
4148 // FIXME: For the moment we do not support combined directives with target and
4149 // teams, so we do not expect to get any thread_limit clause in the provided
4150 // directive. Once we support that, this assertion can be replaced by the
4151 // actual emission of the clause expression.
4152 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4153 "Not expecting clause in directive.");
4154
4155 // If the current target region has a teams region enclosed, we need to get
4156 // the thread limit to pass to the runtime function call. This is done
4157 // by generating the expression in a inlined region. This is required because
4158 // the expression is captured in the enclosing target environment when the
4159 // teams directive is not combined with target.
4160
4161 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4162
4163 // FIXME: Accommodate other combined directives with teams when they become
4164 // available.
4165 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4166 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4167 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4168 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4169 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4170 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4171 /*IsSigned=*/true);
4172 }
4173
4174 // If we have an enclosed teams directive but no thread_limit clause we use
4175 // the default value 0.
4176 return CGF.Builder.getInt32(0);
4177 }
4178
4179 // No teams associated with the directive.
4180 return nullptr;
4181}
4182
Samuel Antaobed3c462015-10-02 16:14:20 +00004183void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
4184 const OMPExecutableDirective &D,
4185 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004186 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00004187 const Expr *IfCond, const Expr *Device,
4188 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004189 if (!CGF.HaveInsertPoint())
4190 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00004191 /// \brief Values for bit flags used to specify the mapping type for
4192 /// offloading.
4193 enum OpenMPOffloadMappingFlags {
4194 /// \brief Allocate memory on the device and move data from host to device.
4195 OMP_MAP_TO = 0x01,
4196 /// \brief Allocate memory on the device and move data from device to host.
4197 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004198 /// \brief The element passed to the device is a pointer.
4199 OMP_MAP_PTR = 0x20,
4200 /// \brief Pass the element to the device by value.
4201 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00004202 };
4203
4204 enum OpenMPOffloadingReservedDeviceIDs {
4205 /// \brief Device ID if the device was not defined, runtime should get it
4206 /// from environment variables in the spec.
4207 OMP_DEVICEID_UNDEF = -1,
4208 };
4209
Samuel Antaoee8fb302016-01-06 13:42:12 +00004210 assert(OutlinedFn && "Invalid outlined function!");
4211
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004212 auto &Ctx = CGF.getContext();
4213
Samuel Antaobed3c462015-10-02 16:14:20 +00004214 // Fill up the arrays with the all the captured variables.
4215 SmallVector<llvm::Value *, 16> BasePointers;
4216 SmallVector<llvm::Value *, 16> Pointers;
4217 SmallVector<llvm::Value *, 16> Sizes;
4218 SmallVector<unsigned, 16> MapTypes;
4219
4220 bool hasVLACaptures = false;
4221
4222 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4223 auto RI = CS.getCapturedRecordDecl()->field_begin();
4224 // auto II = CS.capture_init_begin();
4225 auto CV = CapturedVars.begin();
4226 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
4227 CE = CS.capture_end();
4228 CI != CE; ++CI, ++RI, ++CV) {
4229 StringRef Name;
4230 QualType Ty;
4231 llvm::Value *BasePointer;
4232 llvm::Value *Pointer;
4233 llvm::Value *Size;
4234 unsigned MapType;
4235
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004236 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00004237 if (CI->capturesVariableArrayType()) {
4238 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00004239 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004240 // Copy to the device as an argument. No need to retrieve it.
4241 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00004242 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00004243 } else if (CI->capturesThis()) {
4244 BasePointer = Pointer = *CV;
4245 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004246 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004247 // Default map type.
4248 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004249 } else if (CI->capturesVariableByCopy()) {
4250 MapType = OMP_MAP_BYCOPY;
4251 if (!RI->getType()->isAnyPointerType()) {
4252 // If the field is not a pointer, we need to save the actual value and
4253 // load it as a void pointer.
4254 auto DstAddr = CGF.CreateMemTemp(
4255 Ctx.getUIntPtrType(),
4256 Twine(CI->getCapturedVar()->getName()) + ".casted");
4257 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
4258
4259 auto *SrcAddrVal = CGF.EmitScalarConversion(
4260 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
4261 Ctx.getPointerType(RI->getType()), SourceLocation());
4262 LValue SrcLV =
4263 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
4264
4265 // Store the value using the source type pointer.
4266 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
4267
4268 // Load the value using the destination type pointer.
4269 BasePointer = Pointer =
4270 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
4271 } else {
4272 MapType |= OMP_MAP_PTR;
4273 BasePointer = Pointer = *CV;
4274 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00004275 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004276 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004277 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00004278 BasePointer = Pointer = *CV;
4279
4280 const ReferenceType *PtrTy =
4281 cast<ReferenceType>(RI->getType().getTypePtr());
4282 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004283 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004284 // The default map type for a scalar/complex type is 'to' because by
4285 // default the value doesn't have to be retrieved. For an aggregate type,
4286 // the default is 'tofrom'.
4287 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
4288 : OMP_MAP_TO;
4289 if (ElementType->isAnyPointerType())
4290 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00004291 }
4292
4293 BasePointers.push_back(BasePointer);
4294 Pointers.push_back(Pointer);
4295 Sizes.push_back(Size);
4296 MapTypes.push_back(MapType);
4297 }
4298
4299 // Keep track on whether the host function has to be executed.
4300 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004301 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004302 auto OffloadError = CGF.MakeAddrLValue(
4303 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
4304 OffloadErrorQType);
4305 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
4306 OffloadError);
4307
4308 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004309 auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004310 hasVLACaptures, Device, OutlinedFnID, OffloadError,
Samuel Antaob68e2db2016-03-03 16:20:23 +00004311 OffloadErrorQType, &D](CodeGenFunction &CGF) {
Samuel Antaobed3c462015-10-02 16:14:20 +00004312 unsigned PointerNumVal = BasePointers.size();
4313 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
4314 llvm::Value *BasePointersArray;
4315 llvm::Value *PointersArray;
4316 llvm::Value *SizesArray;
4317 llvm::Value *MapTypesArray;
4318
4319 if (PointerNumVal) {
4320 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004321 QualType PointerArrayType = Ctx.getConstantArrayType(
4322 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004323 /*IndexTypeQuals=*/0);
4324
4325 BasePointersArray =
4326 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
4327 PointersArray =
4328 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
4329
4330 // If we don't have any VLA types, we can use a constant array for the map
4331 // sizes, otherwise we need to fill up the arrays as we do for the
4332 // pointers.
4333 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004334 QualType SizeArrayType = Ctx.getConstantArrayType(
4335 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004336 /*IndexTypeQuals=*/0);
4337 SizesArray =
4338 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
4339 } else {
4340 // We expect all the sizes to be constant, so we collect them to create
4341 // a constant array.
4342 SmallVector<llvm::Constant *, 16> ConstSizes;
4343 for (auto S : Sizes)
4344 ConstSizes.push_back(cast<llvm::Constant>(S));
4345
4346 auto *SizesArrayInit = llvm::ConstantArray::get(
4347 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
4348 auto *SizesArrayGbl = new llvm::GlobalVariable(
4349 CGM.getModule(), SizesArrayInit->getType(),
4350 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4351 SizesArrayInit, ".offload_sizes");
4352 SizesArrayGbl->setUnnamedAddr(true);
4353 SizesArray = SizesArrayGbl;
4354 }
4355
4356 // The map types are always constant so we don't need to generate code to
4357 // fill arrays. Instead, we create an array constant.
4358 llvm::Constant *MapTypesArrayInit =
4359 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
4360 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
4361 CGM.getModule(), MapTypesArrayInit->getType(),
4362 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4363 MapTypesArrayInit, ".offload_maptypes");
4364 MapTypesArrayGbl->setUnnamedAddr(true);
4365 MapTypesArray = MapTypesArrayGbl;
4366
4367 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004368 llvm::Value *BPVal = BasePointers[i];
4369 if (BPVal->getType()->isPointerTy())
4370 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
4371 else {
4372 assert(BPVal->getType()->isIntegerTy() &&
4373 "If not a pointer, the value type must be an integer.");
4374 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
4375 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004376 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
4377 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
4378 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004379 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4380 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004381
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004382 llvm::Value *PVal = Pointers[i];
4383 if (PVal->getType()->isPointerTy())
4384 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
4385 else {
4386 assert(PVal->getType()->isIntegerTy() &&
4387 "If not a pointer, the value type must be an integer.");
4388 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
4389 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004390 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4391 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4392 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004393 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4394 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004395
4396 if (hasVLACaptures) {
4397 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4398 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4399 /*Idx0=*/0,
4400 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004401 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004402 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4403 Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4404 SAddr);
4405 }
4406 }
4407
4408 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4409 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4410 /*Idx0=*/0, /*Idx1=*/0);
4411 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4412 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4413 /*Idx0=*/0,
4414 /*Idx1=*/0);
4415 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4416 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4417 /*Idx0=*/0, /*Idx1=*/0);
4418 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4419 llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4420 /*Idx0=*/0,
4421 /*Idx1=*/0);
4422
4423 } else {
4424 BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4425 PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4426 SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4427 MapTypesArray =
4428 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4429 }
4430
4431 // On top of the arrays that were filled up, the target offloading call
4432 // takes as arguments the device id as well as the host pointer. The host
4433 // pointer is used by the runtime library to identify the current target
4434 // region, so it only has to be unique and not necessarily point to
4435 // anything. It could be the pointer to the outlined function that
4436 // implements the target region, but we aren't using that so that the
4437 // compiler doesn't need to keep that, and could therefore inline the host
4438 // function if proven worthwhile during optimization.
4439
Samuel Antaoee8fb302016-01-06 13:42:12 +00004440 // From this point on, we need to have an ID of the target region defined.
4441 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004442
4443 // Emit device ID if any.
4444 llvm::Value *DeviceID;
4445 if (Device)
4446 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4447 CGM.Int32Ty, /*isSigned=*/true);
4448 else
4449 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4450
Samuel Antaob68e2db2016-03-03 16:20:23 +00004451 // Return value of the runtime offloading call.
4452 llvm::Value *Return;
4453
4454 auto *NumTeams = emitNumTeamsClauseForTargetDirective(*this, CGF, D);
4455 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(*this, CGF, D);
4456
4457 // If we have NumTeams defined this means that we have an enclosed teams
4458 // region. Therefore we also expect to have ThreadLimit defined. These two
4459 // values should be defined in the presence of a teams directive, regardless
4460 // of having any clauses associated. If the user is using teams but no
4461 // clauses, these two values will be the default that should be passed to
4462 // the runtime library - a 32-bit integer with the value zero.
4463 if (NumTeams) {
4464 assert(ThreadLimit && "Thread limit expression should be available along "
4465 "with number of teams.");
4466 llvm::Value *OffloadingArgs[] = {
4467 DeviceID, OutlinedFnID, PointerNum,
4468 BasePointersArray, PointersArray, SizesArray,
4469 MapTypesArray, NumTeams, ThreadLimit};
4470 Return = CGF.EmitRuntimeCall(
4471 createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
4472 } else {
4473 llvm::Value *OffloadingArgs[] = {
4474 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4475 PointersArray, SizesArray, MapTypesArray};
4476 Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4477 OffloadingArgs);
4478 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004479
4480 CGF.EmitStoreOfScalar(Return, OffloadError);
4481 };
4482
Samuel Antaoee8fb302016-01-06 13:42:12 +00004483 // Notify that the host version must be executed.
4484 auto &&ElseGen = [this, OffloadError,
4485 OffloadErrorQType](CodeGenFunction &CGF) {
4486 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4487 OffloadError);
4488 };
4489
4490 // If we have a target function ID it means that we need to support
4491 // offloading, otherwise, just execute on the host. We need to execute on host
4492 // regardless of the conditional in the if clause if, e.g., the user do not
4493 // specify target triples.
4494 if (OutlinedFnID) {
4495 if (IfCond) {
4496 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4497 } else {
4498 CodeGenFunction::RunCleanupsScope Scope(CGF);
4499 ThenGen(CGF);
4500 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004501 } else {
4502 CodeGenFunction::RunCleanupsScope Scope(CGF);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004503 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004504 }
4505
4506 // Check the error code and execute the host version if required.
4507 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4508 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4509 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4510 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4511 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4512
4513 CGF.EmitBlock(OffloadFailedBlock);
4514 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4515 CGF.EmitBranch(OffloadContBlock);
4516
4517 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004518}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004519
4520void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4521 StringRef ParentName) {
4522 if (!S)
4523 return;
4524
4525 // If we find a OMP target directive, codegen the outline function and
4526 // register the result.
4527 // FIXME: Add other directives with target when they become supported.
4528 bool isTargetDirective = isa<OMPTargetDirective>(S);
4529
4530 if (isTargetDirective) {
4531 auto *E = cast<OMPExecutableDirective>(S);
4532 unsigned DeviceID;
4533 unsigned FileID;
4534 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004535 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004536 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004537
4538 // Is this a target region that should not be emitted as an entry point? If
4539 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00004540 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4541 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004542 return;
4543
4544 llvm::Function *Fn;
4545 llvm::Constant *Addr;
4546 emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4547 /*isOffloadEntry=*/true);
4548 assert(Fn && Addr && "Target region emission failed.");
4549 return;
4550 }
4551
4552 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4553 if (!E->getAssociatedStmt())
4554 return;
4555
4556 scanForTargetRegionsFunctions(
4557 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4558 ParentName);
4559 return;
4560 }
4561
4562 // If this is a lambda function, look into its body.
4563 if (auto *L = dyn_cast<LambdaExpr>(S))
4564 S = L->getBody();
4565
4566 // Keep looking for target regions recursively.
4567 for (auto *II : S->children())
4568 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004569}
4570
4571bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4572 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4573
4574 // If emitting code for the host, we do not process FD here. Instead we do
4575 // the normal code generation.
4576 if (!CGM.getLangOpts().OpenMPIsDevice)
4577 return false;
4578
4579 // Try to detect target regions in the function.
4580 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4581
4582 // We should not emit any function othen that the ones created during the
4583 // scanning. Therefore, we signal that this function is completely dealt
4584 // with.
4585 return true;
4586}
4587
4588bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4589 if (!CGM.getLangOpts().OpenMPIsDevice)
4590 return false;
4591
4592 // Check if there are Ctors/Dtors in this declaration and look for target
4593 // regions in it. We use the complete variant to produce the kernel name
4594 // mangling.
4595 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4596 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4597 for (auto *Ctor : RD->ctors()) {
4598 StringRef ParentName =
4599 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4600 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4601 }
4602 auto *Dtor = RD->getDestructor();
4603 if (Dtor) {
4604 StringRef ParentName =
4605 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4606 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4607 }
4608 }
4609
4610 // If we are in target mode we do not emit any global (declare target is not
4611 // implemented yet). Therefore we signal that GD was processed in this case.
4612 return true;
4613}
4614
4615bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4616 auto *VD = GD.getDecl();
4617 if (isa<FunctionDecl>(VD))
4618 return emitTargetFunctions(GD);
4619
4620 return emitTargetGlobalVariable(GD);
4621}
4622
4623llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4624 // If we have offloading in the current module, we need to emit the entries
4625 // now and register the offloading descriptor.
4626 createOffloadEntriesAndInfoMetadata();
4627
4628 // Create and register the offloading binary descriptors. This is the main
4629 // entity that captures all the information about offloading in the current
4630 // compilation unit.
4631 return createOffloadingBinaryDescriptorRegistration();
4632}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004633
4634void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
4635 const OMPExecutableDirective &D,
4636 SourceLocation Loc,
4637 llvm::Value *OutlinedFn,
4638 ArrayRef<llvm::Value *> CapturedVars) {
4639 if (!CGF.HaveInsertPoint())
4640 return;
4641
4642 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4643 CodeGenFunction::RunCleanupsScope Scope(CGF);
4644
4645 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
4646 llvm::Value *Args[] = {
4647 RTLoc,
4648 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
4649 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
4650 llvm::SmallVector<llvm::Value *, 16> RealArgs;
4651 RealArgs.append(std::begin(Args), std::end(Args));
4652 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
4653
4654 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
4655 CGF.EmitRuntimeCall(RTLFn, RealArgs);
4656}
4657
4658void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
4659 llvm::Value *NumTeams,
4660 llvm::Value *ThreadLimit,
4661 SourceLocation Loc) {
4662 if (!CGF.HaveInsertPoint())
4663 return;
4664
4665 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4666
4667 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
4668 llvm::Value *PushNumTeamsArgs[] = {
4669 RTLoc, getThreadID(CGF, Loc), NumTeams, ThreadLimit};
4670 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
4671 PushNumTeamsArgs);
4672}