blob: dedffc2db5a508be983eb13eb2290f27e79c7bfc [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
Alexey Bataev424be922016-03-28 12:52:58 +0000255static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000256 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,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000428 /// \brief dist_schedule types
429 OMP_dist_sch_static_chunked = 91,
430 OMP_dist_sch_static = 92,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000431};
432
433enum OpenMPRTLFunction {
434 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
435 /// kmpc_micro microtask, ...);
436 OMPRTL__kmpc_fork_call,
437 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
438 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
439 OMPRTL__kmpc_threadprivate_cached,
440 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
441 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
442 OMPRTL__kmpc_threadprivate_register,
443 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
444 OMPRTL__kmpc_global_thread_num,
445 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
446 // kmp_critical_name *crit);
447 OMPRTL__kmpc_critical,
448 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
449 // global_tid, kmp_critical_name *crit, uintptr_t hint);
450 OMPRTL__kmpc_critical_with_hint,
451 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
452 // kmp_critical_name *crit);
453 OMPRTL__kmpc_end_critical,
454 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
455 // global_tid);
456 OMPRTL__kmpc_cancel_barrier,
457 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
458 OMPRTL__kmpc_barrier,
459 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
460 OMPRTL__kmpc_for_static_fini,
461 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
462 // global_tid);
463 OMPRTL__kmpc_serialized_parallel,
464 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
465 // global_tid);
466 OMPRTL__kmpc_end_serialized_parallel,
467 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
468 // kmp_int32 num_threads);
469 OMPRTL__kmpc_push_num_threads,
470 // Call to void __kmpc_flush(ident_t *loc);
471 OMPRTL__kmpc_flush,
472 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
473 OMPRTL__kmpc_master,
474 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
475 OMPRTL__kmpc_end_master,
476 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
477 // int end_part);
478 OMPRTL__kmpc_omp_taskyield,
479 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
480 OMPRTL__kmpc_single,
481 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
482 OMPRTL__kmpc_end_single,
483 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
484 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
485 // kmp_routine_entry_t *task_entry);
486 OMPRTL__kmpc_omp_task_alloc,
487 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
488 // new_task);
489 OMPRTL__kmpc_omp_task,
490 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
491 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
492 // kmp_int32 didit);
493 OMPRTL__kmpc_copyprivate,
494 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
495 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
496 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
497 OMPRTL__kmpc_reduce,
498 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
499 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
500 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
501 // *lck);
502 OMPRTL__kmpc_reduce_nowait,
503 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
504 // kmp_critical_name *lck);
505 OMPRTL__kmpc_end_reduce,
506 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
507 // kmp_critical_name *lck);
508 OMPRTL__kmpc_end_reduce_nowait,
509 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
510 // kmp_task_t * new_task);
511 OMPRTL__kmpc_omp_task_begin_if0,
512 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
513 // kmp_task_t * new_task);
514 OMPRTL__kmpc_omp_task_complete_if0,
515 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
516 OMPRTL__kmpc_ordered,
517 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
518 OMPRTL__kmpc_end_ordered,
519 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
520 // global_tid);
521 OMPRTL__kmpc_omp_taskwait,
522 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
523 OMPRTL__kmpc_taskgroup,
524 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
525 OMPRTL__kmpc_end_taskgroup,
526 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
527 // int proc_bind);
528 OMPRTL__kmpc_push_proc_bind,
529 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
530 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
531 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
532 OMPRTL__kmpc_omp_task_with_deps,
533 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
534 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
535 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
536 OMPRTL__kmpc_omp_wait_deps,
537 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
538 // global_tid, kmp_int32 cncl_kind);
539 OMPRTL__kmpc_cancellationpoint,
540 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
541 // kmp_int32 cncl_kind);
542 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000543 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
544 // kmp_int32 num_teams, kmp_int32 thread_limit);
545 OMPRTL__kmpc_push_num_teams,
546 /// \brief Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc,
547 /// kmpc_micro microtask, ...);
548 OMPRTL__kmpc_fork_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000549
550 //
551 // Offloading related calls
552 //
553 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
554 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
555 // *arg_types);
556 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000557 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
558 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
559 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
560 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000561 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
562 OMPRTL__tgt_register_lib,
563 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
564 OMPRTL__tgt_unregister_lib,
565};
566
Alexey Bataev424be922016-03-28 12:52:58 +0000567/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
568/// region.
569class CleanupTy final : public EHScopeStack::Cleanup {
570 PrePostActionTy *Action;
571
572public:
573 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
574 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
575 if (!CGF.HaveInsertPoint())
576 return;
577 Action->Exit(CGF);
578 }
579};
580
Hans Wennborg7eb54642015-09-10 17:07:54 +0000581} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000582
Alexey Bataev424be922016-03-28 12:52:58 +0000583void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
584 CodeGenFunction::RunCleanupsScope Scope(CGF);
585 if (PrePostAction) {
586 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
587 Callback(CodeGen, CGF, *PrePostAction);
588 } else {
589 PrePostActionTy Action;
590 Callback(CodeGen, CGF, Action);
591 }
592}
593
Alexey Bataev18095712014-10-10 12:19:54 +0000594LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000595 return CGF.EmitLoadOfPointerLValue(
596 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
597 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000598}
599
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000600void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000601 if (!CGF.HaveInsertPoint())
602 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000603 // 1.2.2 OpenMP Language Terminology
604 // Structured block - An executable statement with a single entry at the
605 // top and a single exit at the bottom.
606 // The point of exit cannot be a branch out of the structured block.
607 // longjmp() and throw() must not violate the entry/exit criteria.
608 CGF.EHStack.pushTerminate();
Alexey Bataev424be922016-03-28 12:52:58 +0000609 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000610 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000611}
612
Alexey Bataev62b63b12015-03-10 07:28:44 +0000613LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
614 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000615 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
616 getThreadIDVariable()->getType(),
617 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000618}
619
Alexey Bataev9959db52014-05-06 10:08:46 +0000620CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000621 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000622 IdentTy = llvm::StructType::create(
623 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
624 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000625 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000626 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000627
628 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000629}
630
Alexey Bataev91797552015-03-18 04:13:55 +0000631void CGOpenMPRuntime::clear() {
632 InternalVars.clear();
633}
634
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000635static llvm::Function *
636emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
637 const Expr *CombinerInitializer, const VarDecl *In,
638 const VarDecl *Out, bool IsCombiner) {
639 // void .omp_combiner.(Ty *in, Ty *out);
640 auto &C = CGM.getContext();
641 QualType PtrTy = C.getPointerType(Ty).withRestrict();
642 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000643 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
644 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000645 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
646 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000647 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000648 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000649 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000650 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000651 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
652 auto *Fn = llvm::Function::Create(
653 FnTy, llvm::GlobalValue::InternalLinkage,
654 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
655 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000656 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000657 CodeGenFunction CGF(CGM);
658 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
659 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
660 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
661 CodeGenFunction::OMPPrivateScope Scope(CGF);
662 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
663 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
664 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
665 .getAddress();
666 });
667 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
668 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
669 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
670 .getAddress();
671 });
672 (void)Scope.Privatize();
673 CGF.EmitIgnoredExpr(CombinerInitializer);
674 Scope.ForceCleanup();
675 CGF.FinishFunction();
676 return Fn;
677}
678
679void CGOpenMPRuntime::emitUserDefinedReduction(
680 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
681 if (UDRMap.count(D) > 0)
682 return;
683 auto &C = CGM.getContext();
684 if (!In || !Out) {
685 In = &C.Idents.get("omp_in");
686 Out = &C.Idents.get("omp_out");
687 }
688 llvm::Function *Combiner = emitCombinerOrInitializer(
689 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
690 cast<VarDecl>(D->lookup(Out).front()),
691 /*IsCombiner=*/true);
692 llvm::Function *Initializer = nullptr;
693 if (auto *Init = D->getInitializer()) {
694 if (!Priv || !Orig) {
695 Priv = &C.Idents.get("omp_priv");
696 Orig = &C.Idents.get("omp_orig");
697 }
698 Initializer = emitCombinerOrInitializer(
699 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
700 cast<VarDecl>(D->lookup(Priv).front()),
701 /*IsCombiner=*/false);
702 }
703 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
704 if (CGF) {
705 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
706 Decls.second.push_back(D);
707 }
708}
709
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000710std::pair<llvm::Function *, llvm::Function *>
711CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
712 auto I = UDRMap.find(D);
713 if (I != UDRMap.end())
714 return I->second;
715 emitUserDefinedReduction(/*CGF=*/nullptr, D);
716 return UDRMap.lookup(D);
717}
718
John McCall7f416cc2015-09-08 08:05:57 +0000719// Layout information for ident_t.
720static CharUnits getIdentAlign(CodeGenModule &CGM) {
721 return CGM.getPointerAlign();
722}
723static CharUnits getIdentSize(CodeGenModule &CGM) {
724 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
725 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
726}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000727static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000728 // All the fields except the last are i32, so this works beautifully.
729 return unsigned(Field) * CharUnits::fromQuantity(4);
730}
731static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000732 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000733 const llvm::Twine &Name = "") {
734 auto Offset = getOffsetOfIdentField(Field);
735 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
736}
737
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000738llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000739 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
740 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000741 assert(ThreadIDVar->getType()->isPointerType() &&
742 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000743 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
744 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000745 bool HasCancel = false;
746 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
747 HasCancel = OPD->hasCancel();
748 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
749 HasCancel = OPSD->hasCancel();
750 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
751 HasCancel = OPFD->hasCancel();
752 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
753 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000754 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000755 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000756}
757
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000758llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
759 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
760 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000761 assert(!ThreadIDVar->getType()->isPointerType() &&
762 "thread id variable must be of type kmp_int32 for tasks");
763 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
764 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000765 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000766 InnermostKind,
767 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000768 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000769 return CGF.GenerateCapturedStmtFunction(*CS);
770}
771
Alexey Bataev50b3c952016-02-19 10:38:26 +0000772Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000773 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000774 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000775 if (!Entry) {
776 if (!DefaultOpenMPPSource) {
777 // Initialize default location for psource field of ident_t structure of
778 // all ident_t objects. Format is ";file;function;line;column;;".
779 // Taken from
780 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
781 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000782 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000783 DefaultOpenMPPSource =
784 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
785 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000786 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
787 CGM.getModule(), IdentTy, /*isConstant*/ true,
788 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000789 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000790 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000791
792 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000793 llvm::Constant *Values[] = {Zero,
794 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
795 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000796 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
797 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000798 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000799 }
John McCall7f416cc2015-09-08 08:05:57 +0000800 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000801}
802
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000803llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
804 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000805 unsigned Flags) {
806 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000807 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000808 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000809 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000810 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000811
812 assert(CGF.CurFn && "No function in current CodeGenFunction.");
813
John McCall7f416cc2015-09-08 08:05:57 +0000814 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000815 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
816 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000817 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
818
Alexander Musmanc6388682014-12-15 07:07:06 +0000819 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
820 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000821 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000822 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000823 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
824 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000825 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000826 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000827 LocValue = AI;
828
829 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
830 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000831 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000832 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000833 }
834
835 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000836 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000837
Alexey Bataevf002aca2014-05-30 05:48:40 +0000838 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
839 if (OMPDebugLoc == nullptr) {
840 SmallString<128> Buffer2;
841 llvm::raw_svector_ostream OS2(Buffer2);
842 // Build debug location
843 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
844 OS2 << ";" << PLoc.getFilename() << ";";
845 if (const FunctionDecl *FD =
846 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
847 OS2 << FD->getQualifiedNameAsString();
848 }
849 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
850 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
851 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000852 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000853 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000854 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
855
John McCall7f416cc2015-09-08 08:05:57 +0000856 // Our callers always pass this to a runtime function, so for
857 // convenience, go ahead and return a naked pointer.
858 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000859}
860
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000861llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
862 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000863 assert(CGF.CurFn && "No function in current CodeGenFunction.");
864
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000865 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000866 // Check whether we've already cached a load of the thread id in this
867 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000868 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000869 if (I != OpenMPLocThreadIDMap.end()) {
870 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000871 if (ThreadID != nullptr)
872 return ThreadID;
873 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000874 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000875 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000876 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000877 // Check if this an outlined function with thread id passed as argument.
878 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000879 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
880 // If value loaded in entry block, cache it and use it everywhere in
881 // function.
882 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
883 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
884 Elem.second.ThreadID = ThreadID;
885 }
886 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000887 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000888 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000889
890 // This is not an outlined function region - need to call __kmpc_int32
891 // kmpc_global_thread_num(ident_t *loc).
892 // Generate thread id value and cache this value for use across the
893 // function.
894 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
895 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
896 ThreadID =
897 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
898 emitUpdateLocation(CGF, Loc));
899 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
900 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000901 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000902}
903
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000904void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000905 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000906 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
907 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000908 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
909 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
910 UDRMap.erase(D);
911 }
912 FunctionUDRMap.erase(CGF.CurFn);
913 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000914}
915
916llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev424be922016-03-28 12:52:58 +0000917 if (!IdentTy) {
918 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000919 return llvm::PointerType::getUnqual(IdentTy);
920}
921
922llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev424be922016-03-28 12:52:58 +0000923 if (!Kmpc_MicroTy) {
924 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
925 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
926 llvm::PointerType::getUnqual(CGM.Int32Ty)};
927 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
928 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000929 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
930}
931
932llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +0000933CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000934 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +0000935 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000936 case OMPRTL__kmpc_fork_call: {
937 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
938 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000939 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
940 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000941 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000942 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000943 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
944 break;
945 }
946 case OMPRTL__kmpc_global_thread_num: {
947 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000948 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000949 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000950 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000951 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
952 break;
953 }
Alexey Bataev97720002014-11-11 04:05:39 +0000954 case OMPRTL__kmpc_threadprivate_cached: {
955 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
956 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
958 CGM.VoidPtrTy, CGM.SizeTy,
959 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
960 llvm::FunctionType *FnTy =
961 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
962 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
963 break;
964 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000965 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000966 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
967 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000968 llvm::Type *TypeParams[] = {
969 getIdentTyPointerTy(), CGM.Int32Ty,
970 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
971 llvm::FunctionType *FnTy =
972 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
973 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
974 break;
975 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000976 case OMPRTL__kmpc_critical_with_hint: {
977 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
978 // kmp_critical_name *crit, uintptr_t hint);
979 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
980 llvm::PointerType::getUnqual(KmpCriticalNameTy),
981 CGM.IntPtrTy};
982 llvm::FunctionType *FnTy =
983 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
984 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
985 break;
986 }
Alexey Bataev97720002014-11-11 04:05:39 +0000987 case OMPRTL__kmpc_threadprivate_register: {
988 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
989 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
990 // typedef void *(*kmpc_ctor)(void *);
991 auto KmpcCtorTy =
992 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
993 /*isVarArg*/ false)->getPointerTo();
994 // typedef void *(*kmpc_cctor)(void *, void *);
995 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
996 auto KmpcCopyCtorTy =
997 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
998 /*isVarArg*/ false)->getPointerTo();
999 // typedef void (*kmpc_dtor)(void *);
1000 auto KmpcDtorTy =
1001 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1002 ->getPointerTo();
1003 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1004 KmpcCopyCtorTy, KmpcDtorTy};
1005 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1006 /*isVarArg*/ false);
1007 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1008 break;
1009 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001010 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001011 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1012 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001013 llvm::Type *TypeParams[] = {
1014 getIdentTyPointerTy(), CGM.Int32Ty,
1015 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1016 llvm::FunctionType *FnTy =
1017 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1018 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1019 break;
1020 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001021 case OMPRTL__kmpc_cancel_barrier: {
1022 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1023 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001024 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1025 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001026 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1027 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001028 break;
1029 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001030 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001031 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001032 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1033 llvm::FunctionType *FnTy =
1034 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1035 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1036 break;
1037 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001038 case OMPRTL__kmpc_for_static_fini: {
1039 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1040 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1041 llvm::FunctionType *FnTy =
1042 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1043 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1044 break;
1045 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001046 case OMPRTL__kmpc_push_num_threads: {
1047 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1048 // kmp_int32 num_threads)
1049 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1050 CGM.Int32Ty};
1051 llvm::FunctionType *FnTy =
1052 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1053 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1054 break;
1055 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001056 case OMPRTL__kmpc_serialized_parallel: {
1057 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1058 // global_tid);
1059 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1060 llvm::FunctionType *FnTy =
1061 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1062 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1063 break;
1064 }
1065 case OMPRTL__kmpc_end_serialized_parallel: {
1066 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1067 // global_tid);
1068 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1069 llvm::FunctionType *FnTy =
1070 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1071 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1072 break;
1073 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001074 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001075 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001076 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1077 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001078 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001079 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1080 break;
1081 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001082 case OMPRTL__kmpc_master: {
1083 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1084 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1085 llvm::FunctionType *FnTy =
1086 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1087 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1088 break;
1089 }
1090 case OMPRTL__kmpc_end_master: {
1091 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1092 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1093 llvm::FunctionType *FnTy =
1094 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1095 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1096 break;
1097 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001098 case OMPRTL__kmpc_omp_taskyield: {
1099 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1100 // int end_part);
1101 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1102 llvm::FunctionType *FnTy =
1103 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1104 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1105 break;
1106 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001107 case OMPRTL__kmpc_single: {
1108 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1109 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1110 llvm::FunctionType *FnTy =
1111 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1112 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1113 break;
1114 }
1115 case OMPRTL__kmpc_end_single: {
1116 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1117 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1118 llvm::FunctionType *FnTy =
1119 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1120 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1121 break;
1122 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001123 case OMPRTL__kmpc_omp_task_alloc: {
1124 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1125 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1126 // kmp_routine_entry_t *task_entry);
1127 assert(KmpRoutineEntryPtrTy != nullptr &&
1128 "Type kmp_routine_entry_t must be created.");
1129 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1130 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1131 // Return void * and then cast to particular kmp_task_t type.
1132 llvm::FunctionType *FnTy =
1133 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1134 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1135 break;
1136 }
1137 case OMPRTL__kmpc_omp_task: {
1138 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1139 // *new_task);
1140 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1141 CGM.VoidPtrTy};
1142 llvm::FunctionType *FnTy =
1143 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1144 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1145 break;
1146 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001147 case OMPRTL__kmpc_copyprivate: {
1148 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001149 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001150 // kmp_int32 didit);
1151 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1152 auto *CpyFnTy =
1153 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001154 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001155 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1156 CGM.Int32Ty};
1157 llvm::FunctionType *FnTy =
1158 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1159 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1160 break;
1161 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001162 case OMPRTL__kmpc_reduce: {
1163 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1164 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1165 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1166 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1167 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1168 /*isVarArg=*/false);
1169 llvm::Type *TypeParams[] = {
1170 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1171 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1172 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1173 llvm::FunctionType *FnTy =
1174 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1175 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1176 break;
1177 }
1178 case OMPRTL__kmpc_reduce_nowait: {
1179 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1180 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1181 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1182 // *lck);
1183 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1184 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1185 /*isVarArg=*/false);
1186 llvm::Type *TypeParams[] = {
1187 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1188 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1189 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1190 llvm::FunctionType *FnTy =
1191 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1192 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1193 break;
1194 }
1195 case OMPRTL__kmpc_end_reduce: {
1196 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1197 // kmp_critical_name *lck);
1198 llvm::Type *TypeParams[] = {
1199 getIdentTyPointerTy(), CGM.Int32Ty,
1200 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1201 llvm::FunctionType *FnTy =
1202 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1203 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1204 break;
1205 }
1206 case OMPRTL__kmpc_end_reduce_nowait: {
1207 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1208 // kmp_critical_name *lck);
1209 llvm::Type *TypeParams[] = {
1210 getIdentTyPointerTy(), CGM.Int32Ty,
1211 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1212 llvm::FunctionType *FnTy =
1213 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1214 RTLFn =
1215 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1216 break;
1217 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001218 case OMPRTL__kmpc_omp_task_begin_if0: {
1219 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1220 // *new_task);
1221 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1222 CGM.VoidPtrTy};
1223 llvm::FunctionType *FnTy =
1224 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1225 RTLFn =
1226 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1227 break;
1228 }
1229 case OMPRTL__kmpc_omp_task_complete_if0: {
1230 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1231 // *new_task);
1232 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1233 CGM.VoidPtrTy};
1234 llvm::FunctionType *FnTy =
1235 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1236 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1237 /*Name=*/"__kmpc_omp_task_complete_if0");
1238 break;
1239 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001240 case OMPRTL__kmpc_ordered: {
1241 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1242 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1243 llvm::FunctionType *FnTy =
1244 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1245 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1246 break;
1247 }
1248 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001249 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001250 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1251 llvm::FunctionType *FnTy =
1252 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1253 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1254 break;
1255 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001256 case OMPRTL__kmpc_omp_taskwait: {
1257 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1258 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1259 llvm::FunctionType *FnTy =
1260 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1261 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1262 break;
1263 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001264 case OMPRTL__kmpc_taskgroup: {
1265 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1266 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1267 llvm::FunctionType *FnTy =
1268 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1269 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1270 break;
1271 }
1272 case OMPRTL__kmpc_end_taskgroup: {
1273 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1274 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1275 llvm::FunctionType *FnTy =
1276 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1277 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1278 break;
1279 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001280 case OMPRTL__kmpc_push_proc_bind: {
1281 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1282 // int proc_bind)
1283 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1284 llvm::FunctionType *FnTy =
1285 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1286 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1287 break;
1288 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001289 case OMPRTL__kmpc_omp_task_with_deps: {
1290 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1291 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1292 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1293 llvm::Type *TypeParams[] = {
1294 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1295 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1296 llvm::FunctionType *FnTy =
1297 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1298 RTLFn =
1299 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1300 break;
1301 }
1302 case OMPRTL__kmpc_omp_wait_deps: {
1303 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1304 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1305 // kmp_depend_info_t *noalias_dep_list);
1306 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1307 CGM.Int32Ty, CGM.VoidPtrTy,
1308 CGM.Int32Ty, CGM.VoidPtrTy};
1309 llvm::FunctionType *FnTy =
1310 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1311 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1312 break;
1313 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001314 case OMPRTL__kmpc_cancellationpoint: {
1315 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1316 // global_tid, kmp_int32 cncl_kind)
1317 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1318 llvm::FunctionType *FnTy =
1319 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1320 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1321 break;
1322 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001323 case OMPRTL__kmpc_cancel: {
1324 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1325 // kmp_int32 cncl_kind)
1326 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1327 llvm::FunctionType *FnTy =
1328 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1329 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1330 break;
1331 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001332 case OMPRTL__kmpc_push_num_teams: {
1333 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1334 // kmp_int32 num_teams, kmp_int32 num_threads)
1335 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1336 CGM.Int32Ty};
1337 llvm::FunctionType *FnTy =
1338 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1339 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1340 break;
1341 }
1342 case OMPRTL__kmpc_fork_teams: {
1343 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1344 // microtask, ...);
1345 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1346 getKmpc_MicroPointerTy()};
1347 llvm::FunctionType *FnTy =
1348 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1349 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1350 break;
1351 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001352 case OMPRTL__tgt_target: {
1353 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1354 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1355 // *arg_types);
1356 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1357 CGM.VoidPtrTy,
1358 CGM.Int32Ty,
1359 CGM.VoidPtrPtrTy,
1360 CGM.VoidPtrPtrTy,
1361 CGM.SizeTy->getPointerTo(),
1362 CGM.Int32Ty->getPointerTo()};
1363 llvm::FunctionType *FnTy =
1364 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1365 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1366 break;
1367 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001368 case OMPRTL__tgt_target_teams: {
1369 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1370 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1371 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1372 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1373 CGM.VoidPtrTy,
1374 CGM.Int32Ty,
1375 CGM.VoidPtrPtrTy,
1376 CGM.VoidPtrPtrTy,
1377 CGM.SizeTy->getPointerTo(),
1378 CGM.Int32Ty->getPointerTo(),
1379 CGM.Int32Ty,
1380 CGM.Int32Ty};
1381 llvm::FunctionType *FnTy =
1382 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1383 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1384 break;
1385 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001386 case OMPRTL__tgt_register_lib: {
1387 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1388 QualType ParamTy =
1389 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1390 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1391 llvm::FunctionType *FnTy =
1392 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1393 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1394 break;
1395 }
1396 case OMPRTL__tgt_unregister_lib: {
1397 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1398 QualType ParamTy =
1399 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1400 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1401 llvm::FunctionType *FnTy =
1402 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1403 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1404 break;
1405 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001406 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001407 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001408 return RTLFn;
1409}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001410
Alexander Musman21212e42015-03-13 10:38:23 +00001411llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1412 bool IVSigned) {
1413 assert((IVSize == 32 || IVSize == 64) &&
1414 "IV size is not compatible with the omp runtime");
1415 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1416 : "__kmpc_for_static_init_4u")
1417 : (IVSigned ? "__kmpc_for_static_init_8"
1418 : "__kmpc_for_static_init_8u");
1419 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1420 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1421 llvm::Type *TypeParams[] = {
1422 getIdentTyPointerTy(), // loc
1423 CGM.Int32Ty, // tid
1424 CGM.Int32Ty, // schedtype
1425 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1426 PtrTy, // p_lower
1427 PtrTy, // p_upper
1428 PtrTy, // p_stride
1429 ITy, // incr
1430 ITy // chunk
1431 };
1432 llvm::FunctionType *FnTy =
1433 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1434 return CGM.CreateRuntimeFunction(FnTy, Name);
1435}
1436
Alexander Musman92bdaab2015-03-12 13:37:50 +00001437llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1438 bool IVSigned) {
1439 assert((IVSize == 32 || IVSize == 64) &&
1440 "IV size is not compatible with the omp runtime");
1441 auto Name =
1442 IVSize == 32
1443 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1444 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1445 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1446 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1447 CGM.Int32Ty, // tid
1448 CGM.Int32Ty, // schedtype
1449 ITy, // lower
1450 ITy, // upper
1451 ITy, // stride
1452 ITy // chunk
1453 };
1454 llvm::FunctionType *FnTy =
1455 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1456 return CGM.CreateRuntimeFunction(FnTy, Name);
1457}
1458
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001459llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1460 bool IVSigned) {
1461 assert((IVSize == 32 || IVSize == 64) &&
1462 "IV size is not compatible with the omp runtime");
1463 auto Name =
1464 IVSize == 32
1465 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1466 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1467 llvm::Type *TypeParams[] = {
1468 getIdentTyPointerTy(), // loc
1469 CGM.Int32Ty, // tid
1470 };
1471 llvm::FunctionType *FnTy =
1472 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1473 return CGM.CreateRuntimeFunction(FnTy, Name);
1474}
1475
Alexander Musman92bdaab2015-03-12 13:37:50 +00001476llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1477 bool IVSigned) {
1478 assert((IVSize == 32 || IVSize == 64) &&
1479 "IV size is not compatible with the omp runtime");
1480 auto Name =
1481 IVSize == 32
1482 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1483 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1484 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1485 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1486 llvm::Type *TypeParams[] = {
1487 getIdentTyPointerTy(), // loc
1488 CGM.Int32Ty, // tid
1489 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1490 PtrTy, // p_lower
1491 PtrTy, // p_upper
1492 PtrTy // p_stride
1493 };
1494 llvm::FunctionType *FnTy =
1495 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1496 return CGM.CreateRuntimeFunction(FnTy, Name);
1497}
1498
Alexey Bataev97720002014-11-11 04:05:39 +00001499llvm::Constant *
1500CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001501 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1502 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001503 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001504 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001505 Twine(CGM.getMangledName(VD)) + ".cache.");
1506}
1507
John McCall7f416cc2015-09-08 08:05:57 +00001508Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1509 const VarDecl *VD,
1510 Address VDAddr,
1511 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001512 if (CGM.getLangOpts().OpenMPUseTLS &&
1513 CGM.getContext().getTargetInfo().isTLSSupported())
1514 return VDAddr;
1515
John McCall7f416cc2015-09-08 08:05:57 +00001516 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001517 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001518 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1519 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001520 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1521 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001522 return Address(CGF.EmitRuntimeCall(
1523 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1524 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001525}
1526
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001527void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001528 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001529 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1530 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1531 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001532 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1533 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001534 OMPLoc);
1535 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1536 // to register constructor/destructor for variable.
1537 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001538 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1539 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001540 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001541 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001542 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001543}
1544
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001545llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001546 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001547 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001548 if (CGM.getLangOpts().OpenMPUseTLS &&
1549 CGM.getContext().getTargetInfo().isTLSSupported())
1550 return nullptr;
1551
Alexey Bataev97720002014-11-11 04:05:39 +00001552 VD = VD->getDefinition(CGM.getContext());
1553 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1554 ThreadPrivateWithDefinition.insert(VD);
1555 QualType ASTTy = VD->getType();
1556
1557 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1558 auto Init = VD->getAnyInitializer();
1559 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1560 // Generate function that re-emits the declaration's initializer into the
1561 // threadprivate copy of the variable VD
1562 CodeGenFunction CtorCGF(CGM);
1563 FunctionArgList Args;
1564 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1565 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1566 Args.push_back(&Dst);
1567
John McCallc56a8b32016-03-11 04:30:31 +00001568 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1569 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001570 auto FTy = CGM.getTypes().GetFunctionType(FI);
1571 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001572 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001573 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1574 Args, SourceLocation());
1575 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001576 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001577 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001578 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1579 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1580 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001581 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1582 /*IsInitializer=*/true);
1583 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001584 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001585 CGM.getContext().VoidPtrTy, Dst.getLocation());
1586 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1587 CtorCGF.FinishFunction();
1588 Ctor = Fn;
1589 }
1590 if (VD->getType().isDestructedType() != QualType::DK_none) {
1591 // Generate function that emits destructor call for the threadprivate copy
1592 // of the variable VD
1593 CodeGenFunction DtorCGF(CGM);
1594 FunctionArgList Args;
1595 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1596 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1597 Args.push_back(&Dst);
1598
John McCallc56a8b32016-03-11 04:30:31 +00001599 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1600 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001601 auto FTy = CGM.getTypes().GetFunctionType(FI);
1602 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001603 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001604 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1605 SourceLocation());
1606 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1607 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001608 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1609 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001610 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1611 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1612 DtorCGF.FinishFunction();
1613 Dtor = Fn;
1614 }
1615 // Do not emit init function if it is not required.
1616 if (!Ctor && !Dtor)
1617 return nullptr;
1618
1619 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1620 auto CopyCtorTy =
1621 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1622 /*isVarArg=*/false)->getPointerTo();
1623 // Copying constructor for the threadprivate variable.
1624 // Must be NULL - reserved by runtime, but currently it requires that this
1625 // parameter is always NULL. Otherwise it fires assertion.
1626 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1627 if (Ctor == nullptr) {
1628 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1629 /*isVarArg=*/false)->getPointerTo();
1630 Ctor = llvm::Constant::getNullValue(CtorTy);
1631 }
1632 if (Dtor == nullptr) {
1633 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1634 /*isVarArg=*/false)->getPointerTo();
1635 Dtor = llvm::Constant::getNullValue(DtorTy);
1636 }
1637 if (!CGF) {
1638 auto InitFunctionTy =
1639 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1640 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001641 InitFunctionTy, ".__omp_threadprivate_init_.",
1642 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001643 CodeGenFunction InitCGF(CGM);
1644 FunctionArgList ArgList;
1645 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1646 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1647 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001648 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001649 InitCGF.FinishFunction();
1650 return InitFunction;
1651 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001652 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001653 }
1654 return nullptr;
1655}
1656
Alexey Bataev1d677132015-04-22 13:57:31 +00001657/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1658/// function. Here is the logic:
1659/// if (Cond) {
1660/// ThenGen();
1661/// } else {
1662/// ElseGen();
1663/// }
1664static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1665 const RegionCodeGenTy &ThenGen,
1666 const RegionCodeGenTy &ElseGen) {
1667 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1668
1669 // If the condition constant folds and can be elided, try to avoid emitting
1670 // the condition and the dead arm of the if/else.
1671 bool CondConstant;
1672 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev424be922016-03-28 12:52:58 +00001673 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001674 ThenGen(CGF);
Alexey Bataev424be922016-03-28 12:52:58 +00001675 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001676 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001677 return;
1678 }
1679
1680 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1681 // emit the conditional branch.
1682 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1683 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1684 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1685 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1686
1687 // Emit the 'then' code.
1688 CGF.EmitBlock(ThenBlock);
Alexey Bataev424be922016-03-28 12:52:58 +00001689 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001690 CGF.EmitBranch(ContBlock);
1691 // Emit the 'else' code if present.
Alexey Bataev424be922016-03-28 12:52:58 +00001692 // There is no need to emit line number for unconditional branch.
1693 (void)ApplyDebugLocation::CreateEmpty(CGF);
1694 CGF.EmitBlock(ElseBlock);
1695 ElseGen(CGF);
1696 // There is no need to emit line number for unconditional branch.
1697 (void)ApplyDebugLocation::CreateEmpty(CGF);
1698 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001699 // Emit the continuation block for code after the if.
1700 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001701}
1702
Alexey Bataev1d677132015-04-22 13:57:31 +00001703void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1704 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001705 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001706 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001707 if (!CGF.HaveInsertPoint())
1708 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001709 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev424be922016-03-28 12:52:58 +00001710 RegionCodeGenTy ThenGen = [OutlinedFn, CapturedVars,
1711 RTLoc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001712 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev424be922016-03-28 12:52:58 +00001713 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001714 llvm::Value *Args[] = {
1715 RTLoc,
1716 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev424be922016-03-28 12:52:58 +00001717 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001718 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1719 RealArgs.append(std::begin(Args), std::end(Args));
1720 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1721
Alexey Bataev424be922016-03-28 12:52:58 +00001722 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001723 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1724 };
Alexey Bataev424be922016-03-28 12:52:58 +00001725 RegionCodeGenTy ElseGen = [OutlinedFn, CapturedVars, RTLoc,
1726 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
1727 auto &RT = CGF.CGM.getOpenMPRuntime();
1728 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001729 // Build calls:
1730 // __kmpc_serialized_parallel(&Loc, GTid);
1731 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev424be922016-03-28 12:52:58 +00001732 CGF.EmitRuntimeCall(
1733 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001734
Alexey Bataev1d677132015-04-22 13:57:31 +00001735 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev424be922016-03-28 12:52:58 +00001736 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001737 Address ZeroAddr =
Alexey Bataev424be922016-03-28 12:52:58 +00001738 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1739 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001740 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001741 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1742 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1743 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1744 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001745 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001746
Alexey Bataev1d677132015-04-22 13:57:31 +00001747 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev424be922016-03-28 12:52:58 +00001748 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001749 CGF.EmitRuntimeCall(
Alexey Bataev424be922016-03-28 12:52:58 +00001750 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1751 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001752 };
Alexey Bataev424be922016-03-28 12:52:58 +00001753 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001754 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev424be922016-03-28 12:52:58 +00001755 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001756 ThenGen(CGF);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001757}
1758
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001759// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001760// thread-ID variable (it is passed in a first argument of the outlined function
1761// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1762// regular serial code region, get thread ID by calling kmp_int32
1763// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1764// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001765Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1766 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001767 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001768 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001769 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001770 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001771
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001772 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001773 auto Int32Ty =
1774 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1775 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1776 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001777 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001778
1779 return ThreadIDTemp;
1780}
1781
Alexey Bataev97720002014-11-11 04:05:39 +00001782llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001783CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001784 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001785 SmallString<256> Buffer;
1786 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001787 Out << Name;
1788 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001789 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1790 if (Elem.second) {
1791 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001792 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001793 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001794 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001795
David Blaikie13156b62014-11-19 03:06:06 +00001796 return Elem.second = new llvm::GlobalVariable(
1797 CGM.getModule(), Ty, /*IsConstant*/ false,
1798 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1799 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001800}
1801
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001802llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001803 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001804 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001805}
1806
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001807namespace {
Alexey Bataev424be922016-03-28 12:52:58 +00001808/// Common pre(post)-action for different OpenMP constructs.
1809class CommonActionTy final : public PrePostActionTy {
1810 llvm::Value *EnterCallee;
1811 ArrayRef<llvm::Value *> EnterArgs;
1812 llvm::Value *ExitCallee;
1813 ArrayRef<llvm::Value *> ExitArgs;
1814 bool Conditional;
1815 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001816
1817public:
Alexey Bataev424be922016-03-28 12:52:58 +00001818 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
1819 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
1820 bool Conditional = false)
1821 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
1822 ExitArgs(ExitArgs), Conditional(Conditional) {}
1823 void Enter(CodeGenFunction &CGF) override {
1824 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
1825 if (Conditional) {
1826 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
1827 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1828 ContBlock = CGF.createBasicBlock("omp_if.end");
1829 // Generate the branch (If-stmt)
1830 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1831 CGF.EmitBlock(ThenBlock);
1832 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00001833 }
Alexey Bataev424be922016-03-28 12:52:58 +00001834 void Done(CodeGenFunction &CGF) {
1835 // Emit the rest of blocks/branches
1836 CGF.EmitBranch(ContBlock);
1837 CGF.EmitBlock(ContBlock, true);
1838 }
1839 void Exit(CodeGenFunction &CGF) override {
1840 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001841 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001842};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001843} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001844
1845void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1846 StringRef CriticalName,
1847 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001848 SourceLocation Loc, const Expr *Hint) {
1849 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001850 // CriticalOpGen();
1851 // __kmpc_end_critical(ident_t *, gtid, Lock);
1852 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001853 if (!CGF.HaveInsertPoint())
1854 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001855 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1856 getCriticalRegionLock(CriticalName)};
Alexey Bataev424be922016-03-28 12:52:58 +00001857 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
1858 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00001859 if (Hint) {
Alexey Bataev424be922016-03-28 12:52:58 +00001860 EnterArgs.push_back(CGF.Builder.CreateIntCast(
1861 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
1862 }
1863 CommonActionTy Action(
1864 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
1865 : OMPRTL__kmpc_critical),
1866 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
1867 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001868 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001869}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001870
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001871void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001872 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001873 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001874 if (!CGF.HaveInsertPoint())
1875 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001876 // if(__kmpc_master(ident_t *, gtid)) {
1877 // MasterOpGen();
1878 // __kmpc_end_master(ident_t *, gtid);
1879 // }
1880 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001881 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev424be922016-03-28 12:52:58 +00001882 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
1883 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
1884 /*Conditional=*/true);
1885 MasterOpGen.setAction(Action);
1886 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
1887 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001888}
1889
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001890void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1891 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001892 if (!CGF.HaveInsertPoint())
1893 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001894 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1895 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001896 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001897 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001898 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001899}
1900
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001901void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1902 const RegionCodeGenTy &TaskgroupOpGen,
1903 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001904 if (!CGF.HaveInsertPoint())
1905 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001906 // __kmpc_taskgroup(ident_t *, gtid);
1907 // TaskgroupOpGen();
1908 // __kmpc_end_taskgroup(ident_t *, gtid);
1909 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev424be922016-03-28 12:52:58 +00001910 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1911 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
1912 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1913 Args);
1914 TaskgroupOpGen.setAction(Action);
1915 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001916}
1917
John McCall7f416cc2015-09-08 08:05:57 +00001918/// Given an array of pointers to variables, project the address of a
1919/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001920static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1921 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001922 // Pull out the pointer to the variable.
1923 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001924 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001925 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1926
1927 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001928 Addr = CGF.Builder.CreateElementBitCast(
1929 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001930 return Addr;
1931}
1932
Alexey Bataeva63048e2015-03-23 06:18:07 +00001933static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001934 CodeGenModule &CGM, llvm::Type *ArgsType,
1935 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1936 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001937 auto &C = CGM.getContext();
1938 // void copy_func(void *LHSArg, void *RHSArg);
1939 FunctionArgList Args;
1940 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1941 C.VoidPtrTy);
1942 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1943 C.VoidPtrTy);
1944 Args.push_back(&LHSArg);
1945 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00001946 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001947 auto *Fn = llvm::Function::Create(
1948 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1949 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001950 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001951 CodeGenFunction CGF(CGM);
1952 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001953 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001954 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001955 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1956 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1957 ArgsType), CGF.getPointerAlign());
1958 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1959 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1960 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001961 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1962 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1963 // ...
1964 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001965 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001966 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1967 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1968
1969 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1970 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1971
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001972 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1973 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001974 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001975 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001976 CGF.FinishFunction();
1977 return Fn;
1978}
1979
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001980void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001981 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001982 SourceLocation Loc,
1983 ArrayRef<const Expr *> CopyprivateVars,
1984 ArrayRef<const Expr *> SrcExprs,
1985 ArrayRef<const Expr *> DstExprs,
1986 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001987 if (!CGF.HaveInsertPoint())
1988 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001989 assert(CopyprivateVars.size() == SrcExprs.size() &&
1990 CopyprivateVars.size() == DstExprs.size() &&
1991 CopyprivateVars.size() == AssignmentOps.size());
1992 auto &C = CGM.getContext();
1993 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001994 // if(__kmpc_single(ident_t *, gtid)) {
1995 // SingleOpGen();
1996 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001997 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001998 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001999 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2000 // <copy_func>, did_it);
2001
John McCall7f416cc2015-09-08 08:05:57 +00002002 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002003 if (!CopyprivateVars.empty()) {
2004 // int32 did_it = 0;
2005 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2006 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002007 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002008 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002009 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002010 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev424be922016-03-28 12:52:58 +00002011 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2012 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2013 /*Conditional=*/true);
2014 SingleOpGen.setAction(Action);
2015 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2016 if (DidIt.isValid()) {
2017 // did_it = 1;
2018 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2019 }
2020 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002021 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2022 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002023 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002024 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2025 auto CopyprivateArrayTy =
2026 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2027 /*IndexTypeQuals=*/0);
2028 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002029 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002030 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2031 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002032 Address Elem = CGF.Builder.CreateConstArrayGEP(
2033 CopyprivateList, I, CGF.getPointerSize());
2034 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002035 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002036 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2037 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002038 }
2039 // Build function that copies private values from single region to all other
2040 // threads in the corresponding parallel region.
2041 auto *CpyFn = emitCopyprivateCopyFunction(
2042 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002043 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002044 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002045 Address CL =
2046 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2047 CGF.VoidPtrTy);
2048 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002049 llvm::Value *Args[] = {
2050 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2051 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002052 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002053 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002054 CpyFn, // void (*) (void *, void *) <copy_func>
2055 DidItVal // i32 did_it
2056 };
2057 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2058 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002059}
2060
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002061void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2062 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002063 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002064 if (!CGF.HaveInsertPoint())
2065 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002066 // __kmpc_ordered(ident_t *, gtid);
2067 // OrderedOpGen();
2068 // __kmpc_end_ordered(ident_t *, gtid);
2069 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002070 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002071 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev424be922016-03-28 12:52:58 +00002072 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2073 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2074 Args);
2075 OrderedOpGen.setAction(Action);
2076 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2077 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002078 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002079 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002080}
2081
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002082void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002083 OpenMPDirectiveKind Kind, bool EmitChecks,
2084 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002085 if (!CGF.HaveInsertPoint())
2086 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002087 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002088 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002089 unsigned Flags;
2090 if (Kind == OMPD_for)
2091 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2092 else if (Kind == OMPD_sections)
2093 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2094 else if (Kind == OMPD_single)
2095 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2096 else if (Kind == OMPD_barrier)
2097 Flags = OMP_IDENT_BARRIER_EXPL;
2098 else
2099 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002100 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2101 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002102 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2103 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002104 if (auto *OMPRegionInfo =
2105 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002106 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002107 auto *Result = CGF.EmitRuntimeCall(
2108 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002109 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002110 // if (__kmpc_cancel_barrier()) {
2111 // exit from construct;
2112 // }
2113 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2114 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2115 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2116 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2117 CGF.EmitBlock(ExitBB);
2118 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002119 auto CancelDestination =
2120 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002121 CGF.EmitBranchThroughCleanup(CancelDestination);
2122 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2123 }
2124 return;
2125 }
2126 }
2127 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002128}
2129
Alexander Musmanc6388682014-12-15 07:07:06 +00002130/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2131static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002132 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002133 switch (ScheduleKind) {
2134 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002135 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2136 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002137 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002138 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002139 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002140 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002141 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002142 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2143 case OMPC_SCHEDULE_auto:
2144 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002145 case OMPC_SCHEDULE_unknown:
2146 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002147 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002148 }
2149 llvm_unreachable("Unexpected runtime schedule");
2150}
2151
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002152/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2153static OpenMPSchedType
2154getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2155 // only static is allowed for dist_schedule
2156 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2157}
2158
Alexander Musmanc6388682014-12-15 07:07:06 +00002159bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2160 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002161 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002162 return Schedule == OMP_sch_static;
2163}
2164
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002165bool CGOpenMPRuntime::isStaticNonchunked(
2166 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2167 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2168 return Schedule == OMP_dist_sch_static;
2169}
2170
2171
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002172bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002173 auto Schedule =
2174 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002175 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2176 return Schedule != OMP_sch_static;
2177}
2178
John McCall7f416cc2015-09-08 08:05:57 +00002179void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2180 SourceLocation Loc,
2181 OpenMPScheduleClauseKind ScheduleKind,
2182 unsigned IVSize, bool IVSigned,
2183 bool Ordered, llvm::Value *UB,
2184 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002185 if (!CGF.HaveInsertPoint())
2186 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002187 OpenMPSchedType Schedule =
2188 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002189 assert(Ordered ||
2190 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2191 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2192 // Call __kmpc_dispatch_init(
2193 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2194 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2195 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002196
John McCall7f416cc2015-09-08 08:05:57 +00002197 // If the Chunk was not specified in the clause - use default value 1.
2198 if (Chunk == nullptr)
2199 Chunk = CGF.Builder.getIntN(IVSize, 1);
2200 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002201 emitUpdateLocation(CGF, Loc),
2202 getThreadID(CGF, Loc),
2203 CGF.Builder.getInt32(Schedule), // Schedule type
2204 CGF.Builder.getIntN(IVSize, 0), // Lower
2205 UB, // Upper
2206 CGF.Builder.getIntN(IVSize, 1), // Stride
2207 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002208 };
2209 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2210}
2211
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002212static void emitForStaticInitCall(CodeGenFunction &CGF,
2213 SourceLocation Loc,
2214 llvm::Value * UpdateLocation,
2215 llvm::Value * ThreadId,
2216 llvm::Constant * ForStaticInitFunction,
2217 OpenMPSchedType Schedule,
2218 unsigned IVSize, bool IVSigned, bool Ordered,
2219 Address IL, Address LB, Address UB,
2220 Address ST, llvm::Value *Chunk) {
2221 if (!CGF.HaveInsertPoint())
2222 return;
2223
2224 assert(!Ordered);
2225 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2226 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2227 Schedule == OMP_dist_sch_static ||
2228 Schedule == OMP_dist_sch_static_chunked);
2229
2230 // Call __kmpc_for_static_init(
2231 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2232 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2233 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2234 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2235 if (Chunk == nullptr) {
2236 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2237 Schedule == OMP_dist_sch_static) &&
2238 "expected static non-chunked schedule");
2239 // If the Chunk was not specified in the clause - use default value 1.
2240 Chunk = CGF.Builder.getIntN(IVSize, 1);
2241 } else {
2242 assert((Schedule == OMP_sch_static_chunked ||
2243 Schedule == OMP_ord_static_chunked ||
2244 Schedule == OMP_dist_sch_static_chunked) &&
2245 "expected static chunked schedule");
2246 }
2247 llvm::Value *Args[] = {
2248 UpdateLocation,
2249 ThreadId,
2250 CGF.Builder.getInt32(Schedule), // Schedule type
2251 IL.getPointer(), // &isLastIter
2252 LB.getPointer(), // &LB
2253 UB.getPointer(), // &UB
2254 ST.getPointer(), // &Stride
2255 CGF.Builder.getIntN(IVSize, 1), // Incr
2256 Chunk // Chunk
2257 };
2258 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2259}
2260
John McCall7f416cc2015-09-08 08:05:57 +00002261void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2262 SourceLocation Loc,
2263 OpenMPScheduleClauseKind ScheduleKind,
2264 unsigned IVSize, bool IVSigned,
2265 bool Ordered, Address IL, Address LB,
2266 Address UB, Address ST,
2267 llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002268 OpenMPSchedType ScheduleNum = getRuntimeSchedule(ScheduleKind, Chunk != nullptr,
2269 Ordered);
2270 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2271 auto *ThreadId = getThreadID(CGF, Loc);
2272 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2273 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2274 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
2275}
John McCall7f416cc2015-09-08 08:05:57 +00002276
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002277void CGOpenMPRuntime::emitDistributeStaticInit(CodeGenFunction &CGF,
2278 SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind,
2279 unsigned IVSize, bool IVSigned,
2280 bool Ordered, Address IL, Address LB,
2281 Address UB, Address ST,
2282 llvm::Value *Chunk) {
2283 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2284 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2285 auto *ThreadId = getThreadID(CGF, Loc);
2286 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2287 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2288 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002289}
2290
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002291void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2292 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002293 if (!CGF.HaveInsertPoint())
2294 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002295 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002296 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002297 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2298 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002299}
2300
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002301void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2302 SourceLocation Loc,
2303 unsigned IVSize,
2304 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002305 if (!CGF.HaveInsertPoint())
2306 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002307 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002308 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002309 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2310}
2311
Alexander Musman92bdaab2015-03-12 13:37:50 +00002312llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2313 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002314 bool IVSigned, Address IL,
2315 Address LB, Address UB,
2316 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002317 // Call __kmpc_dispatch_next(
2318 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2319 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2320 // kmp_int[32|64] *p_stride);
2321 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002322 emitUpdateLocation(CGF, Loc),
2323 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002324 IL.getPointer(), // &isLastIter
2325 LB.getPointer(), // &Lower
2326 UB.getPointer(), // &Upper
2327 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002328 };
2329 llvm::Value *Call =
2330 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2331 return CGF.EmitScalarConversion(
2332 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002333 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002334}
2335
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002336void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2337 llvm::Value *NumThreads,
2338 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002339 if (!CGF.HaveInsertPoint())
2340 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002341 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2342 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002343 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002344 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002345 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2346 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002347}
2348
Alexey Bataev7f210c62015-06-18 13:40:03 +00002349void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2350 OpenMPProcBindClauseKind ProcBind,
2351 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002352 if (!CGF.HaveInsertPoint())
2353 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002354 // Constants for proc bind value accepted by the runtime.
2355 enum ProcBindTy {
2356 ProcBindFalse = 0,
2357 ProcBindTrue,
2358 ProcBindMaster,
2359 ProcBindClose,
2360 ProcBindSpread,
2361 ProcBindIntel,
2362 ProcBindDefault
2363 } RuntimeProcBind;
2364 switch (ProcBind) {
2365 case OMPC_PROC_BIND_master:
2366 RuntimeProcBind = ProcBindMaster;
2367 break;
2368 case OMPC_PROC_BIND_close:
2369 RuntimeProcBind = ProcBindClose;
2370 break;
2371 case OMPC_PROC_BIND_spread:
2372 RuntimeProcBind = ProcBindSpread;
2373 break;
2374 case OMPC_PROC_BIND_unknown:
2375 llvm_unreachable("Unsupported proc_bind value.");
2376 }
2377 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2378 llvm::Value *Args[] = {
2379 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2380 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2381 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2382}
2383
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002384void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2385 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002386 if (!CGF.HaveInsertPoint())
2387 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002388 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002389 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2390 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002391}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002392
Alexey Bataev62b63b12015-03-10 07:28:44 +00002393namespace {
2394/// \brief Indexes of fields for type kmp_task_t.
2395enum KmpTaskTFields {
2396 /// \brief List of shared variables.
2397 KmpTaskTShareds,
2398 /// \brief Task routine.
2399 KmpTaskTRoutine,
2400 /// \brief Partition id for the untied tasks.
2401 KmpTaskTPartId,
2402 /// \brief Function with call of destructors for private variables.
2403 KmpTaskTDestructors,
2404};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002405} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002406
Samuel Antaoee8fb302016-01-06 13:42:12 +00002407bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2408 // FIXME: Add other entries type when they become supported.
2409 return OffloadEntriesTargetRegion.empty();
2410}
2411
2412/// \brief Initialize target region entry.
2413void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2414 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2415 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002416 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002417 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2418 "only required for the device "
2419 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002420 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002421 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2422 ++OffloadingEntriesNum;
2423}
2424
2425void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2426 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2427 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002428 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002429 // If we are emitting code for a target, the entry is already initialized,
2430 // only has to be registered.
2431 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002432 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002433 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002434 auto &Entry =
2435 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002436 assert(Entry.isValid() && "Entry not initialized!");
2437 Entry.setAddress(Addr);
2438 Entry.setID(ID);
2439 return;
2440 } else {
2441 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002442 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002443 }
2444}
2445
2446bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002447 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2448 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002449 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2450 if (PerDevice == OffloadEntriesTargetRegion.end())
2451 return false;
2452 auto PerFile = PerDevice->second.find(FileID);
2453 if (PerFile == PerDevice->second.end())
2454 return false;
2455 auto PerParentName = PerFile->second.find(ParentName);
2456 if (PerParentName == PerFile->second.end())
2457 return false;
2458 auto PerLine = PerParentName->second.find(LineNum);
2459 if (PerLine == PerParentName->second.end())
2460 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002461 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002462 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002463 return false;
2464 return true;
2465}
2466
2467void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2468 const OffloadTargetRegionEntryInfoActTy &Action) {
2469 // Scan all target region entries and perform the provided action.
2470 for (auto &D : OffloadEntriesTargetRegion)
2471 for (auto &F : D.second)
2472 for (auto &P : F.second)
2473 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002474 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002475}
2476
2477/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2478/// \a Codegen. This is used to emit the two functions that register and
2479/// unregister the descriptor of the current compilation unit.
2480static llvm::Function *
2481createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2482 const RegionCodeGenTy &Codegen) {
2483 auto &C = CGM.getContext();
2484 FunctionArgList Args;
2485 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2486 /*Id=*/nullptr, C.VoidPtrTy);
2487 Args.push_back(&DummyPtr);
2488
2489 CodeGenFunction CGF(CGM);
2490 GlobalDecl();
John McCallc56a8b32016-03-11 04:30:31 +00002491 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002492 auto FTy = CGM.getTypes().GetFunctionType(FI);
2493 auto *Fn =
2494 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2495 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2496 Codegen(CGF);
2497 CGF.FinishFunction();
2498 return Fn;
2499}
2500
2501llvm::Function *
2502CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2503
2504 // If we don't have entries or if we are emitting code for the device, we
2505 // don't need to do anything.
2506 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2507 return nullptr;
2508
2509 auto &M = CGM.getModule();
2510 auto &C = CGM.getContext();
2511
2512 // Get list of devices we care about
2513 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2514
2515 // We should be creating an offloading descriptor only if there are devices
2516 // specified.
2517 assert(!Devices.empty() && "No OpenMP offloading devices??");
2518
2519 // Create the external variables that will point to the begin and end of the
2520 // host entries section. These will be defined by the linker.
2521 auto *OffloadEntryTy =
2522 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2523 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2524 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002525 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002526 ".omp_offloading.entries_begin");
2527 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2528 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002529 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002530 ".omp_offloading.entries_end");
2531
2532 // Create all device images
2533 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2534 auto *DeviceImageTy = cast<llvm::StructType>(
2535 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2536
2537 for (unsigned i = 0; i < Devices.size(); ++i) {
2538 StringRef T = Devices[i].getTriple();
2539 auto *ImgBegin = new llvm::GlobalVariable(
2540 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002541 /*Initializer=*/nullptr,
2542 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002543 auto *ImgEnd = new llvm::GlobalVariable(
2544 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002545 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002546
2547 llvm::Constant *Dev =
2548 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2549 HostEntriesBegin, HostEntriesEnd, nullptr);
2550 DeviceImagesEntires.push_back(Dev);
2551 }
2552
2553 // Create device images global array.
2554 llvm::ArrayType *DeviceImagesInitTy =
2555 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2556 llvm::Constant *DeviceImagesInit =
2557 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2558
2559 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2560 M, DeviceImagesInitTy, /*isConstant=*/true,
2561 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2562 ".omp_offloading.device_images");
2563 DeviceImages->setUnnamedAddr(true);
2564
2565 // This is a Zero array to be used in the creation of the constant expressions
2566 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2567 llvm::Constant::getNullValue(CGM.Int32Ty)};
2568
2569 // Create the target region descriptor.
2570 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2571 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2572 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2573 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2574 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2575 Index),
2576 HostEntriesBegin, HostEntriesEnd, nullptr);
2577
2578 auto *Desc = new llvm::GlobalVariable(
2579 M, BinaryDescriptorTy, /*isConstant=*/true,
2580 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2581 ".omp_offloading.descriptor");
2582
2583 // Emit code to register or unregister the descriptor at execution
2584 // startup or closing, respectively.
2585
2586 // Create a variable to drive the registration and unregistration of the
2587 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2588 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2589 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2590 IdentInfo, C.CharTy);
2591
2592 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev424be922016-03-28 12:52:58 +00002593 CGM, ".omp_offloading.descriptor_unreg",
2594 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002595 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2596 Desc);
2597 });
2598 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev424be922016-03-28 12:52:58 +00002599 CGM, ".omp_offloading.descriptor_reg",
2600 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002601 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2602 Desc);
2603 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2604 });
2605 return RegFn;
2606}
2607
Samuel Antao2de62b02016-02-13 23:35:10 +00002608void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2609 llvm::Constant *Addr, uint64_t Size) {
2610 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002611 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2612 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2613 llvm::LLVMContext &C = CGM.getModule().getContext();
2614 llvm::Module &M = CGM.getModule();
2615
2616 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002617 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002618
2619 // Create constant string with the name.
2620 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2621
2622 llvm::GlobalVariable *Str =
2623 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2624 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2625 ".omp_offloading.entry_name");
2626 Str->setUnnamedAddr(true);
2627 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2628
2629 // Create the entry struct.
2630 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2631 TgtOffloadEntryType, AddrPtr, StrPtr,
2632 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2633 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2634 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2635 EntryInit, ".omp_offloading.entry");
2636
2637 // The entry has to be created in the section the linker expects it to be.
2638 Entry->setSection(".omp_offloading.entries");
2639 // We can't have any padding between symbols, so we need to have 1-byte
2640 // alignment.
2641 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002642}
2643
2644void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2645 // Emit the offloading entries and metadata so that the device codegen side
2646 // can
2647 // easily figure out what to emit. The produced metadata looks like this:
2648 //
2649 // !omp_offload.info = !{!1, ...}
2650 //
2651 // Right now we only generate metadata for function that contain target
2652 // regions.
2653
2654 // If we do not have entries, we dont need to do anything.
2655 if (OffloadEntriesInfoManager.empty())
2656 return;
2657
2658 llvm::Module &M = CGM.getModule();
2659 llvm::LLVMContext &C = M.getContext();
2660 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2661 OrderedEntries(OffloadEntriesInfoManager.size());
2662
2663 // Create the offloading info metadata node.
2664 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2665
2666 // Auxiliar methods to create metadata values and strings.
2667 auto getMDInt = [&](unsigned v) {
2668 return llvm::ConstantAsMetadata::get(
2669 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2670 };
2671
2672 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2673
2674 // Create function that emits metadata for each target region entry;
2675 auto &&TargetRegionMetadataEmitter = [&](
2676 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002677 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2678 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2679 // Generate metadata for target regions. Each entry of this metadata
2680 // contains:
2681 // - Entry 0 -> Kind of this type of metadata (0).
2682 // - Entry 1 -> Device ID of the file where the entry was identified.
2683 // - Entry 2 -> File ID of the file where the entry was identified.
2684 // - Entry 3 -> Mangled name of the function where the entry was identified.
2685 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002686 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002687 // The first element of the metadata node is the kind.
2688 Ops.push_back(getMDInt(E.getKind()));
2689 Ops.push_back(getMDInt(DeviceID));
2690 Ops.push_back(getMDInt(FileID));
2691 Ops.push_back(getMDString(ParentName));
2692 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002693 Ops.push_back(getMDInt(E.getOrder()));
2694
2695 // Save this entry in the right position of the ordered entries array.
2696 OrderedEntries[E.getOrder()] = &E;
2697
2698 // Add metadata to the named metadata node.
2699 MD->addOperand(llvm::MDNode::get(C, Ops));
2700 };
2701
2702 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2703 TargetRegionMetadataEmitter);
2704
2705 for (auto *E : OrderedEntries) {
2706 assert(E && "All ordered entries must exist!");
2707 if (auto *CE =
2708 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2709 E)) {
2710 assert(CE->getID() && CE->getAddress() &&
2711 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002712 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002713 } else
2714 llvm_unreachable("Unsupported entry kind.");
2715 }
2716}
2717
2718/// \brief Loads all the offload entries information from the host IR
2719/// metadata.
2720void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2721 // If we are in target mode, load the metadata from the host IR. This code has
2722 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2723
2724 if (!CGM.getLangOpts().OpenMPIsDevice)
2725 return;
2726
2727 if (CGM.getLangOpts().OMPHostIRFile.empty())
2728 return;
2729
2730 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2731 if (Buf.getError())
2732 return;
2733
2734 llvm::LLVMContext C;
2735 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2736
2737 if (ME.getError())
2738 return;
2739
2740 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2741 if (!MD)
2742 return;
2743
2744 for (auto I : MD->operands()) {
2745 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2746
2747 auto getMDInt = [&](unsigned Idx) {
2748 llvm::ConstantAsMetadata *V =
2749 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2750 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2751 };
2752
2753 auto getMDString = [&](unsigned Idx) {
2754 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2755 return V->getString();
2756 };
2757
2758 switch (getMDInt(0)) {
2759 default:
2760 llvm_unreachable("Unexpected metadata!");
2761 break;
2762 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2763 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2764 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2765 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2766 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002767 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002768 break;
2769 }
2770 }
2771}
2772
Alexey Bataev62b63b12015-03-10 07:28:44 +00002773void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2774 if (!KmpRoutineEntryPtrTy) {
2775 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2776 auto &C = CGM.getContext();
2777 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2778 FunctionProtoType::ExtProtoInfo EPI;
2779 KmpRoutineEntryPtrQTy = C.getPointerType(
2780 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2781 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2782 }
2783}
2784
Alexey Bataevc71a4092015-09-11 10:29:41 +00002785static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2786 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002787 auto *Field = FieldDecl::Create(
2788 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2789 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2790 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2791 Field->setAccess(AS_public);
2792 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002793 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002794}
2795
Samuel Antaoee8fb302016-01-06 13:42:12 +00002796QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2797
2798 // Make sure the type of the entry is already created. This is the type we
2799 // have to create:
2800 // struct __tgt_offload_entry{
2801 // void *addr; // Pointer to the offload entry info.
2802 // // (function or global)
2803 // char *name; // Name of the function or global.
2804 // size_t size; // Size of the entry info (0 if it a function).
2805 // };
2806 if (TgtOffloadEntryQTy.isNull()) {
2807 ASTContext &C = CGM.getContext();
2808 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2809 RD->startDefinition();
2810 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2811 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2812 addFieldToRecordDecl(C, RD, C.getSizeType());
2813 RD->completeDefinition();
2814 TgtOffloadEntryQTy = C.getRecordType(RD);
2815 }
2816 return TgtOffloadEntryQTy;
2817}
2818
2819QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2820 // These are the types we need to build:
2821 // struct __tgt_device_image{
2822 // void *ImageStart; // Pointer to the target code start.
2823 // void *ImageEnd; // Pointer to the target code end.
2824 // // We also add the host entries to the device image, as it may be useful
2825 // // for the target runtime to have access to that information.
2826 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2827 // // the entries.
2828 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2829 // // entries (non inclusive).
2830 // };
2831 if (TgtDeviceImageQTy.isNull()) {
2832 ASTContext &C = CGM.getContext();
2833 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2834 RD->startDefinition();
2835 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2836 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2837 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2838 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2839 RD->completeDefinition();
2840 TgtDeviceImageQTy = C.getRecordType(RD);
2841 }
2842 return TgtDeviceImageQTy;
2843}
2844
2845QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2846 // struct __tgt_bin_desc{
2847 // int32_t NumDevices; // Number of devices supported.
2848 // __tgt_device_image *DeviceImages; // Arrays of device images
2849 // // (one per device).
2850 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2851 // // entries.
2852 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2853 // // entries (non inclusive).
2854 // };
2855 if (TgtBinaryDescriptorQTy.isNull()) {
2856 ASTContext &C = CGM.getContext();
2857 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2858 RD->startDefinition();
2859 addFieldToRecordDecl(
2860 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2861 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2862 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2863 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2864 RD->completeDefinition();
2865 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2866 }
2867 return TgtBinaryDescriptorQTy;
2868}
2869
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002870namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002871struct PrivateHelpersTy {
2872 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2873 const VarDecl *PrivateElemInit)
2874 : Original(Original), PrivateCopy(PrivateCopy),
2875 PrivateElemInit(PrivateElemInit) {}
2876 const VarDecl *Original;
2877 const VarDecl *PrivateCopy;
2878 const VarDecl *PrivateElemInit;
2879};
2880typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002881} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002882
Alexey Bataev9e034042015-05-05 04:05:12 +00002883static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002884createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002885 if (!Privates.empty()) {
2886 auto &C = CGM.getContext();
2887 // Build struct .kmp_privates_t. {
2888 // /* private vars */
2889 // };
2890 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2891 RD->startDefinition();
2892 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002893 auto *VD = Pair.second.Original;
2894 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002895 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002896 auto *FD = addFieldToRecordDecl(C, RD, Type);
2897 if (VD->hasAttrs()) {
2898 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2899 E(VD->getAttrs().end());
2900 I != E; ++I)
2901 FD->addAttr(*I);
2902 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002903 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002904 RD->completeDefinition();
2905 return RD;
2906 }
2907 return nullptr;
2908}
2909
Alexey Bataev9e034042015-05-05 04:05:12 +00002910static RecordDecl *
2911createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002912 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002913 auto &C = CGM.getContext();
2914 // Build struct kmp_task_t {
2915 // void * shareds;
2916 // kmp_routine_entry_t routine;
2917 // kmp_int32 part_id;
2918 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002919 // };
2920 auto *RD = C.buildImplicitRecord("kmp_task_t");
2921 RD->startDefinition();
2922 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2923 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2924 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2925 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002926 RD->completeDefinition();
2927 return RD;
2928}
2929
2930static RecordDecl *
2931createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002932 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002933 auto &C = CGM.getContext();
2934 // Build struct kmp_task_t_with_privates {
2935 // kmp_task_t task_data;
2936 // .kmp_privates_t. privates;
2937 // };
2938 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2939 RD->startDefinition();
2940 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002941 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2942 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2943 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002944 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002945 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002946}
2947
2948/// \brief Emit a proxy function which accepts kmp_task_t as the second
2949/// argument.
2950/// \code
2951/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002952/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2953/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002954/// return 0;
2955/// }
2956/// \endcode
2957static llvm::Value *
2958emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002959 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2960 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002961 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2962 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002963 auto &C = CGM.getContext();
2964 FunctionArgList Args;
2965 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2966 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002967 /*Id=*/nullptr,
2968 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002969 Args.push_back(&GtidArg);
2970 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002971 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00002972 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002973 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2974 auto *TaskEntry =
2975 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2976 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002977 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002978 CodeGenFunction CGF(CGM);
2979 CGF.disableDebugInfo();
2980 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2981
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002982 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2983 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002984 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002985 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002986 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2987 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2988 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002989 auto *KmpTaskTWithPrivatesQTyRD =
2990 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002991 LValue Base =
2992 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002993 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2994 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2995 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
2996 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
2997
2998 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
2999 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003000 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003001 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003002 CGF.ConvertTypeForMem(SharedsPtrTy));
3003
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003004 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3005 llvm::Value *PrivatesParam;
3006 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3007 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3008 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003009 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003010 } else {
3011 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3012 }
3013
3014 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
3015 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003016 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3017 CGF.EmitStoreThroughLValue(
3018 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003019 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003020 CGF.FinishFunction();
3021 return TaskEntry;
3022}
3023
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003024static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3025 SourceLocation Loc,
3026 QualType KmpInt32Ty,
3027 QualType KmpTaskTWithPrivatesPtrQTy,
3028 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003029 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003030 FunctionArgList Args;
3031 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3032 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003033 /*Id=*/nullptr,
3034 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003035 Args.push_back(&GtidArg);
3036 Args.push_back(&TaskTypeArg);
3037 FunctionType::ExtInfo Info;
3038 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003039 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003040 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3041 auto *DestructorFn =
3042 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3043 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003044 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3045 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003046 CodeGenFunction CGF(CGM);
3047 CGF.disableDebugInfo();
3048 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3049 Args);
3050
Alexey Bataev31300ed2016-02-04 11:27:03 +00003051 LValue Base = CGF.EmitLoadOfPointerLValue(
3052 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3053 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003054 auto *KmpTaskTWithPrivatesQTyRD =
3055 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3056 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003057 Base = CGF.EmitLValueForField(Base, *FI);
3058 for (auto *Field :
3059 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3060 if (auto DtorKind = Field->getType().isDestructedType()) {
3061 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3062 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3063 }
3064 }
3065 CGF.FinishFunction();
3066 return DestructorFn;
3067}
3068
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003069/// \brief Emit a privates mapping function for correct handling of private and
3070/// firstprivate variables.
3071/// \code
3072/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3073/// **noalias priv1,..., <tyn> **noalias privn) {
3074/// *priv1 = &.privates.priv1;
3075/// ...;
3076/// *privn = &.privates.privn;
3077/// }
3078/// \endcode
3079static llvm::Value *
3080emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003081 ArrayRef<const Expr *> PrivateVars,
3082 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003083 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003084 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003085 auto &C = CGM.getContext();
3086 FunctionArgList Args;
3087 ImplicitParamDecl TaskPrivatesArg(
3088 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3089 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3090 Args.push_back(&TaskPrivatesArg);
3091 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3092 unsigned Counter = 1;
3093 for (auto *E: PrivateVars) {
3094 Args.push_back(ImplicitParamDecl::Create(
3095 C, /*DC=*/nullptr, Loc,
3096 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3097 .withConst()
3098 .withRestrict()));
3099 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3100 PrivateVarsPos[VD] = Counter;
3101 ++Counter;
3102 }
3103 for (auto *E : FirstprivateVars) {
3104 Args.push_back(ImplicitParamDecl::Create(
3105 C, /*DC=*/nullptr, Loc,
3106 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3107 .withConst()
3108 .withRestrict()));
3109 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3110 PrivateVarsPos[VD] = Counter;
3111 ++Counter;
3112 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003113 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003114 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003115 auto *TaskPrivatesMapTy =
3116 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3117 auto *TaskPrivatesMap = llvm::Function::Create(
3118 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3119 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003120 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3121 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003122 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003123 CodeGenFunction CGF(CGM);
3124 CGF.disableDebugInfo();
3125 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3126 TaskPrivatesMapFnInfo, Args);
3127
3128 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003129 LValue Base = CGF.EmitLoadOfPointerLValue(
3130 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3131 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003132 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3133 Counter = 0;
3134 for (auto *Field : PrivatesQTyRD->fields()) {
3135 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3136 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003137 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003138 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3139 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003140 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003141 ++Counter;
3142 }
3143 CGF.FinishFunction();
3144 return TaskPrivatesMap;
3145}
3146
Alexey Bataev9e034042015-05-05 04:05:12 +00003147static int array_pod_sort_comparator(const PrivateDataTy *P1,
3148 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003149 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3150}
3151
3152void CGOpenMPRuntime::emitTaskCall(
3153 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3154 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00003155 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003156 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3157 ArrayRef<const Expr *> PrivateCopies,
3158 ArrayRef<const Expr *> FirstprivateVars,
3159 ArrayRef<const Expr *> FirstprivateCopies,
3160 ArrayRef<const Expr *> FirstprivateInits,
3161 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003162 if (!CGF.HaveInsertPoint())
3163 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003164 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00003165 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003166 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003167 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003168 for (auto *E : PrivateVars) {
3169 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3170 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003171 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003172 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3173 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003174 ++I;
3175 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003176 I = FirstprivateCopies.begin();
3177 auto IElemInitRef = FirstprivateInits.begin();
3178 for (auto *E : FirstprivateVars) {
3179 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3180 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003181 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003182 PrivateHelpersTy(
3183 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3184 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003185 ++I;
3186 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003187 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003188 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3189 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003190 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3191 // Build type kmp_routine_entry_t (if not built yet).
3192 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003193 // Build type kmp_task_t (if not built yet).
3194 if (KmpTaskTQTy.isNull()) {
3195 KmpTaskTQTy = C.getRecordType(
3196 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
3197 }
3198 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003199 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003200 auto *KmpTaskTWithPrivatesQTyRD =
3201 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3202 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3203 QualType KmpTaskTWithPrivatesPtrQTy =
3204 C.getPointerType(KmpTaskTWithPrivatesQTy);
3205 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3206 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003207 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003208 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3209
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003210 // Emit initial values for private copies (if any).
3211 llvm::Value *TaskPrivatesMap = nullptr;
3212 auto *TaskPrivatesMapTy =
3213 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3214 3)
3215 ->getType();
3216 if (!Privates.empty()) {
3217 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3218 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3219 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3220 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3221 TaskPrivatesMap, TaskPrivatesMapTy);
3222 } else {
3223 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3224 cast<llvm::PointerType>(TaskPrivatesMapTy));
3225 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003226 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3227 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003228 auto *TaskEntry = emitProxyTaskFunction(
3229 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003230 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003231
3232 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3233 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3234 // kmp_routine_entry_t *task_entry);
3235 // Task flags. Format is taken from
3236 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3237 // description of kmp_tasking_flags struct.
3238 const unsigned TiedFlag = 0x1;
3239 const unsigned FinalFlag = 0x2;
3240 unsigned Flags = Tied ? TiedFlag : 0;
3241 auto *TaskFlags =
3242 Final.getPointer()
3243 ? CGF.Builder.CreateSelect(Final.getPointer(),
3244 CGF.Builder.getInt32(FinalFlag),
3245 CGF.Builder.getInt32(/*C=*/0))
3246 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3247 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003248 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003249 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3250 getThreadID(CGF, Loc), TaskFlags,
3251 KmpTaskTWithPrivatesTySize, SharedsSize,
3252 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3253 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003254 auto *NewTask = CGF.EmitRuntimeCall(
3255 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003256 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3257 NewTask, KmpTaskTWithPrivatesPtrTy);
3258 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3259 KmpTaskTWithPrivatesQTy);
3260 LValue TDBase =
3261 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003262 // Fill the data in the resulting kmp_task_t record.
3263 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003264 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003265 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003266 KmpTaskSharedsPtr =
3267 Address(CGF.EmitLoadOfScalar(
3268 CGF.EmitLValueForField(
3269 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3270 KmpTaskTShareds)),
3271 Loc),
3272 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003273 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003274 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003275 // Emit initial values for private copies (if any).
3276 bool NeedsCleanup = false;
3277 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003278 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3279 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003280 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003281 LValue SharedsBase;
3282 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003283 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003284 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3285 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3286 SharedsTy);
3287 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003288 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3289 cast<CapturedStmt>(*D.getAssociatedStmt()));
3290 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003291 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003292 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003293 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003294 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003295 if (auto *Elem = Pair.second.PrivateElemInit) {
3296 auto *OriginalVD = Pair.second.Original;
3297 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3298 auto SharedRefLValue =
3299 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003300 SharedRefLValue = CGF.MakeAddrLValue(
3301 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3302 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003303 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003304 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003305 // Initialize firstprivate array.
3306 if (!isa<CXXConstructExpr>(Init) ||
3307 CGF.isTrivialInitializer(Init)) {
3308 // Perform simple memcpy.
3309 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003310 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003311 } else {
3312 // Initialize firstprivate array using element-by-element
3313 // intialization.
3314 CGF.EmitOMPAggregateAssign(
3315 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003316 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003317 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003318 // Clean up any temporaries needed by the initialization.
3319 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003320 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003321 return SrcElement;
3322 });
3323 (void)InitScope.Privatize();
3324 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003325 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3326 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003327 CGF.EmitAnyExprToMem(Init, DestElement,
3328 Init->getType().getQualifiers(),
3329 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003330 });
3331 }
3332 } else {
3333 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003334 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003335 return SharedRefLValue.getAddress();
3336 });
3337 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003338 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003339 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3340 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003341 }
3342 } else {
3343 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3344 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003345 }
3346 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003347 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003348 }
3349 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003350 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003351 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003352 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3353 KmpTaskTWithPrivatesPtrQTy,
3354 KmpTaskTWithPrivatesQTy)
3355 : llvm::ConstantPointerNull::get(
3356 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3357 LValue Destructor = CGF.EmitLValueForField(
3358 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3359 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3360 DestructorFn, KmpRoutineEntryPtrTy),
3361 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003362
3363 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003364 Address DependenciesArray = Address::invalid();
3365 unsigned NumDependencies = Dependences.size();
3366 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003367 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003368 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003369 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3370 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003371 QualType FlagsTy =
3372 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003373 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3374 if (KmpDependInfoTy.isNull()) {
3375 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3376 KmpDependInfoRD->startDefinition();
3377 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3378 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3379 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3380 KmpDependInfoRD->completeDefinition();
3381 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3382 } else {
3383 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3384 }
John McCall7f416cc2015-09-08 08:05:57 +00003385 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003386 // Define type kmp_depend_info[<Dependences.size()>];
3387 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003388 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003389 ArrayType::Normal, /*IndexTypeQuals=*/0);
3390 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00003391 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
3392 for (unsigned i = 0; i < NumDependencies; ++i) {
3393 const Expr *E = Dependences[i].second;
3394 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003395 llvm::Value *Size;
3396 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003397 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3398 LValue UpAddrLVal =
3399 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3400 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003401 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003402 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003403 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003404 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3405 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003406 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003407 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003408 auto Base = CGF.MakeAddrLValue(
3409 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003410 KmpDependInfoTy);
3411 // deps[i].base_addr = &<Dependences[i].second>;
3412 auto BaseAddrLVal = CGF.EmitLValueForField(
3413 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003414 CGF.EmitStoreOfScalar(
3415 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3416 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003417 // deps[i].len = sizeof(<Dependences[i].second>);
3418 auto LenLVal = CGF.EmitLValueForField(
3419 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3420 CGF.EmitStoreOfScalar(Size, LenLVal);
3421 // deps[i].flags = <Dependences[i].first>;
3422 RTLDependenceKindTy DepKind;
3423 switch (Dependences[i].first) {
3424 case OMPC_DEPEND_in:
3425 DepKind = DepIn;
3426 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003427 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003428 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003429 case OMPC_DEPEND_inout:
3430 DepKind = DepInOut;
3431 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003432 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003433 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003434 case OMPC_DEPEND_unknown:
3435 llvm_unreachable("Unknown task dependence type");
3436 }
3437 auto FlagsLVal = CGF.EmitLValueForField(
3438 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3439 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3440 FlagsLVal);
3441 }
John McCall7f416cc2015-09-08 08:05:57 +00003442 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3443 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003444 CGF.VoidPtrTy);
3445 }
3446
Alexey Bataev62b63b12015-03-10 07:28:44 +00003447 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3448 // libcall.
3449 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3450 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003451 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3452 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3453 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3454 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003455 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003456 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003457 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3458 llvm::Value *DepTaskArgs[7];
3459 if (NumDependencies) {
3460 DepTaskArgs[0] = UpLoc;
3461 DepTaskArgs[1] = ThreadID;
3462 DepTaskArgs[2] = NewTask;
3463 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3464 DepTaskArgs[4] = DependenciesArray.getPointer();
3465 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3466 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3467 }
Alexey Bataev424be922016-03-28 12:52:58 +00003468 RegionCodeGenTy ThenCodeGen = [NumDependencies, &TaskArgs, &DepTaskArgs](
3469 CodeGenFunction &CGF, PrePostActionTy &) {
3470 // TODO: add check for untied tasks.
3471 auto &RT = CGF.CGM.getOpenMPRuntime();
John McCall7f416cc2015-09-08 08:05:57 +00003472 if (NumDependencies) {
Alexey Bataev424be922016-03-28 12:52:58 +00003473 CGF.EmitRuntimeCall(
3474 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3475 DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00003476 } else {
Alexey Bataev424be922016-03-28 12:52:58 +00003477 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00003478 TaskArgs);
3479 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003480 };
John McCall7f416cc2015-09-08 08:05:57 +00003481
3482 llvm::Value *DepWaitTaskArgs[6];
3483 if (NumDependencies) {
3484 DepWaitTaskArgs[0] = UpLoc;
3485 DepWaitTaskArgs[1] = ThreadID;
3486 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3487 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3488 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3489 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3490 }
Alexey Bataev424be922016-03-28 12:52:58 +00003491 RegionCodeGenTy ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy,
3492 TaskEntry, NumDependencies, &DepWaitTaskArgs](
3493 CodeGenFunction &CGF, PrePostActionTy &) {
3494 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003495 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3496 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3497 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3498 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3499 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003500 if (NumDependencies)
Alexey Bataev424be922016-03-28 12:52:58 +00003501 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003502 DepWaitTaskArgs);
Alexey Bataev424be922016-03-28 12:52:58 +00003503 // Call proxy_task_entry(gtid, new_task);
3504 RegionCodeGenTy CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
3505 CodeGenFunction &CGF, PrePostActionTy &Action) {
3506 Action.Enter(CGF);
3507 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3508 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3509 };
3510
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003511 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3512 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003513 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3514 // kmp_task_t *new_task);
Alexey Bataev424be922016-03-28 12:52:58 +00003515 CommonActionTy Action(
3516 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
3517 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
3518 CodeGen.setAction(Action);
3519 CodeGen(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003520 };
John McCall7f416cc2015-09-08 08:05:57 +00003521
Alexey Bataev424be922016-03-28 12:52:58 +00003522 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00003523 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev424be922016-03-28 12:52:58 +00003524 else
Alexey Bataev1d677132015-04-22 13:57:31 +00003525 ThenCodeGen(CGF);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003526}
3527
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003528/// \brief Emit reduction operation for each element of array (required for
3529/// array sections) LHS op = RHS.
3530/// \param Type Type of array.
3531/// \param LHSVar Variable on the left side of the reduction operation
3532/// (references element of array in original variable).
3533/// \param RHSVar Variable on the right side of the reduction operation
3534/// (references element of array in original variable).
3535/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3536/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003537static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003538 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3539 const VarDecl *RHSVar,
3540 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3541 const Expr *, const Expr *)> &RedOpGen,
3542 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3543 const Expr *UpExpr = nullptr) {
3544 // Perform element-by-element initialization.
3545 QualType ElementTy;
3546 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3547 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3548
3549 // Drill down to the base element type on both arrays.
3550 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3551 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3552
3553 auto RHSBegin = RHSAddr.getPointer();
3554 auto LHSBegin = LHSAddr.getPointer();
3555 // Cast from pointer to array type to pointer to single element.
3556 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3557 // The basic structure here is a while-do loop.
3558 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3559 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3560 auto IsEmpty =
3561 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3562 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3563
3564 // Enter the loop body, making that address the current address.
3565 auto EntryBB = CGF.Builder.GetInsertBlock();
3566 CGF.EmitBlock(BodyBB);
3567
3568 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3569
3570 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3571 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3572 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3573 Address RHSElementCurrent =
3574 Address(RHSElementPHI,
3575 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3576
3577 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3578 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3579 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3580 Address LHSElementCurrent =
3581 Address(LHSElementPHI,
3582 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3583
3584 // Emit copy.
3585 CodeGenFunction::OMPPrivateScope Scope(CGF);
3586 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3587 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3588 Scope.Privatize();
3589 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3590 Scope.ForceCleanup();
3591
3592 // Shift the address forward by one element.
3593 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3594 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3595 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3596 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3597 // Check whether we've reached the end.
3598 auto Done =
3599 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3600 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3601 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3602 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3603
3604 // Done.
3605 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3606}
3607
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003608/// Emit reduction combiner. If the combiner is a simple expression emit it as
3609/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
3610/// UDR combiner function.
3611static void emitReductionCombiner(CodeGenFunction &CGF,
3612 const Expr *ReductionOp) {
3613 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
3614 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
3615 if (auto *DRE =
3616 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
3617 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
3618 std::pair<llvm::Function *, llvm::Function *> Reduction =
3619 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
3620 RValue Func = RValue::get(Reduction.first);
3621 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
3622 CGF.EmitIgnoredExpr(ReductionOp);
3623 return;
3624 }
3625 CGF.EmitIgnoredExpr(ReductionOp);
3626}
3627
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003628static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3629 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003630 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003631 ArrayRef<const Expr *> LHSExprs,
3632 ArrayRef<const Expr *> RHSExprs,
3633 ArrayRef<const Expr *> ReductionOps) {
3634 auto &C = CGM.getContext();
3635
3636 // void reduction_func(void *LHSArg, void *RHSArg);
3637 FunctionArgList Args;
3638 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3639 C.VoidPtrTy);
3640 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3641 C.VoidPtrTy);
3642 Args.push_back(&LHSArg);
3643 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00003644 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003645 auto *Fn = llvm::Function::Create(
3646 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3647 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003648 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003649 CodeGenFunction CGF(CGM);
3650 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3651
3652 // Dst = (void*[n])(LHSArg);
3653 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003654 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3655 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3656 ArgsType), CGF.getPointerAlign());
3657 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3658 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3659 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003660
3661 // ...
3662 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3663 // ...
3664 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003665 auto IPriv = Privates.begin();
3666 unsigned Idx = 0;
3667 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003668 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3669 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003670 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003671 });
3672 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3673 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003674 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003675 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003676 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003677 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003678 // Get array size and emit VLA type.
3679 ++Idx;
3680 Address Elem =
3681 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3682 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003683 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3684 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003685 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003686 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003687 CGF.EmitVariablyModifiedType(PrivTy);
3688 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003689 }
3690 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003691 IPriv = Privates.begin();
3692 auto ILHS = LHSExprs.begin();
3693 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003694 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003695 if ((*IPriv)->getType()->isArrayType()) {
3696 // Emit reduction for array section.
3697 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3698 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003699 EmitOMPAggregateReduction(
3700 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3701 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
3702 emitReductionCombiner(CGF, E);
3703 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003704 } else
3705 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003706 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003707 ++IPriv;
3708 ++ILHS;
3709 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003710 }
3711 Scope.ForceCleanup();
3712 CGF.FinishFunction();
3713 return Fn;
3714}
3715
Alexey Bataev424be922016-03-28 12:52:58 +00003716static void emitSingleReductionCombiner(CodeGenFunction &CGF,
3717 const Expr *ReductionOp,
3718 const Expr *PrivateRef,
3719 const DeclRefExpr *LHS,
3720 const DeclRefExpr *RHS) {
3721 if (PrivateRef->getType()->isArrayType()) {
3722 // Emit reduction for array section.
3723 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
3724 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
3725 EmitOMPAggregateReduction(
3726 CGF, PrivateRef->getType(), LHSVar, RHSVar,
3727 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
3728 emitReductionCombiner(CGF, ReductionOp);
3729 });
3730 } else
3731 // Emit reduction for array subscript or single variable.
3732 emitReductionCombiner(CGF, ReductionOp);
3733}
3734
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003735void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003736 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003737 ArrayRef<const Expr *> LHSExprs,
3738 ArrayRef<const Expr *> RHSExprs,
3739 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003740 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003741 if (!CGF.HaveInsertPoint())
3742 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003743 // Next code should be emitted for reduction:
3744 //
3745 // static kmp_critical_name lock = { 0 };
3746 //
3747 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3748 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3749 // ...
3750 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3751 // *(Type<n>-1*)rhs[<n>-1]);
3752 // }
3753 //
3754 // ...
3755 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3756 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3757 // RedList, reduce_func, &<lock>)) {
3758 // case 1:
3759 // ...
3760 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3761 // ...
3762 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3763 // break;
3764 // case 2:
3765 // ...
3766 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3767 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003768 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003769 // break;
3770 // default:;
3771 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003772 //
3773 // if SimpleReduction is true, only the next code is generated:
3774 // ...
3775 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3776 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003777
3778 auto &C = CGM.getContext();
3779
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003780 if (SimpleReduction) {
3781 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003782 auto IPriv = Privates.begin();
3783 auto ILHS = LHSExprs.begin();
3784 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003785 for (auto *E : ReductionOps) {
Alexey Bataev424be922016-03-28 12:52:58 +00003786 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3787 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00003788 ++IPriv;
3789 ++ILHS;
3790 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003791 }
3792 return;
3793 }
3794
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003795 // 1. Build a list of reduction variables.
3796 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003797 auto Size = RHSExprs.size();
3798 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003799 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003800 // Reserve place for array size.
3801 ++Size;
3802 }
3803 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003804 QualType ReductionArrayTy =
3805 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3806 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003807 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003808 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003809 auto IPriv = Privates.begin();
3810 unsigned Idx = 0;
3811 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003812 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003813 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003814 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003815 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003816 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3817 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003818 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003819 // Store array size.
3820 ++Idx;
3821 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3822 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003823 llvm::Value *Size = CGF.Builder.CreateIntCast(
3824 CGF.getVLASize(
3825 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3826 .first,
3827 CGF.SizeTy, /*isSigned=*/false);
3828 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3829 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003830 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003831 }
3832
3833 // 2. Emit reduce_func().
3834 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003835 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3836 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003837
3838 // 3. Create static kmp_critical_name lock = { 0 };
3839 auto *Lock = getCriticalRegionLock(".reduction");
3840
3841 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3842 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003843 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003844 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003845 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003846 auto *RL =
3847 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3848 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003849 llvm::Value *Args[] = {
3850 IdentTLoc, // ident_t *<loc>
3851 ThreadId, // i32 <gtid>
3852 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3853 ReductionArrayTySize, // size_type sizeof(RedList)
3854 RL, // void *RedList
3855 ReductionFn, // void (*) (void *, void *) <reduce_func>
3856 Lock // kmp_critical_name *&<lock>
3857 };
3858 auto Res = CGF.EmitRuntimeCall(
3859 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3860 : OMPRTL__kmpc_reduce),
3861 Args);
3862
3863 // 5. Build switch(res)
3864 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3865 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3866
3867 // 6. Build case 1:
3868 // ...
3869 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3870 // ...
3871 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3872 // break;
3873 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3874 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3875 CGF.EmitBlock(Case1BB);
3876
Alexey Bataev424be922016-03-28 12:52:58 +00003877 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3878 llvm::Value *EndArgs[] = {
3879 IdentTLoc, // ident_t *<loc>
3880 ThreadId, // i32 <gtid>
3881 Lock // kmp_critical_name *&<lock>
3882 };
3883 RegionCodeGenTy CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
3884 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003885 auto IPriv = Privates.begin();
3886 auto ILHS = LHSExprs.begin();
3887 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003888 for (auto *E : ReductionOps) {
Alexey Bataev424be922016-03-28 12:52:58 +00003889 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3890 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00003891 ++IPriv;
3892 ++ILHS;
3893 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003894 }
Alexey Bataev424be922016-03-28 12:52:58 +00003895 };
3896 CommonActionTy Action(
3897 nullptr, llvm::None,
3898 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3899 : OMPRTL__kmpc_end_reduce),
3900 EndArgs);
3901 CodeGen.setAction(Action);
3902 CodeGen(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003903
3904 CGF.EmitBranch(DefaultBB);
3905
3906 // 7. Build case 2:
3907 // ...
3908 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3909 // ...
3910 // break;
3911 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3912 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3913 CGF.EmitBlock(Case2BB);
3914
Alexey Bataev424be922016-03-28 12:52:58 +00003915 RegionCodeGenTy AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs,
3916 &ReductionOps](CodeGenFunction &CGF,
3917 PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003918 auto ILHS = LHSExprs.begin();
3919 auto IRHS = RHSExprs.begin();
3920 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003921 for (auto *E : ReductionOps) {
Alexey Bataev424be922016-03-28 12:52:58 +00003922 const Expr *XExpr = nullptr;
3923 const Expr *EExpr = nullptr;
3924 const Expr *UpExpr = nullptr;
3925 BinaryOperatorKind BO = BO_Comma;
3926 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3927 if (BO->getOpcode() == BO_Assign) {
3928 XExpr = BO->getLHS();
3929 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003930 }
Alexey Bataev424be922016-03-28 12:52:58 +00003931 }
3932 // Try to emit update expression as a simple atomic.
3933 auto *RHSExpr = UpExpr;
3934 if (RHSExpr) {
3935 // Analyze RHS part of the whole expression.
3936 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3937 RHSExpr->IgnoreParenImpCasts())) {
3938 // If this is a conditional operator, analyze its condition for
3939 // min/max reduction operator.
3940 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00003941 }
Alexey Bataev424be922016-03-28 12:52:58 +00003942 if (auto *BORHS =
3943 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3944 EExpr = BORHS->getRHS();
3945 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003946 }
Alexey Bataev424be922016-03-28 12:52:58 +00003947 }
3948 if (XExpr) {
3949 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3950 auto &&AtomicRedGen = [BO, VD, IPriv,
3951 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3952 const Expr *EExpr, const Expr *UpExpr) {
3953 LValue X = CGF.EmitLValue(XExpr);
3954 RValue E;
3955 if (EExpr)
3956 E = CGF.EmitAnyExpr(EExpr);
3957 CGF.EmitOMPAtomicSimpleUpdateExpr(
3958 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
3959 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
3960 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3961 PrivateScope.addPrivate(
3962 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3963 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3964 CGF.emitOMPSimpleStore(
3965 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3966 VD->getType().getNonReferenceType(), Loc);
3967 return LHSTemp;
3968 });
3969 (void)PrivateScope.Privatize();
3970 return CGF.EmitAnyExpr(UpExpr);
3971 });
3972 };
3973 if ((*IPriv)->getType()->isArrayType()) {
3974 // Emit atomic reduction for array section.
3975 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3976 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3977 AtomicRedGen, XExpr, EExpr, UpExpr);
3978 } else
3979 // Emit atomic reduction for array subscript or single variable.
3980 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3981 } else {
3982 // Emit as a critical region.
3983 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
3984 const Expr *, const Expr *) {
3985 auto &RT = CGF.CGM.getOpenMPRuntime();
3986 RT.emitCriticalRegion(
3987 CGF, ".atomic_reduction",
3988 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
3989 Action.Enter(CGF);
3990 emitReductionCombiner(CGF, E);
3991 },
3992 Loc);
3993 };
3994 if ((*IPriv)->getType()->isArrayType()) {
3995 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3996 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3997 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3998 CritRedGen);
3999 } else
4000 CritRedGen(CGF, nullptr, nullptr, nullptr);
4001 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004002 ++ILHS;
4003 ++IRHS;
4004 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004005 }
Alexey Bataev424be922016-03-28 12:52:58 +00004006 };
4007 if (!WithNowait) {
4008 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4009 llvm::Value *EndArgs[] = {
4010 IdentTLoc, // ident_t *<loc>
4011 ThreadId, // i32 <gtid>
4012 Lock // kmp_critical_name *&<lock>
4013 };
4014 CommonActionTy Action(nullptr, llvm::None,
4015 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4016 EndArgs);
4017 AtomicCodeGen.setAction(Action);
4018 AtomicCodeGen(CGF);
4019 } else
4020 AtomicCodeGen(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004021
4022 CGF.EmitBranch(DefaultBB);
4023 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4024}
4025
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004026void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4027 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004028 if (!CGF.HaveInsertPoint())
4029 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004030 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4031 // global_tid);
4032 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4033 // Ignore return result until untied tasks are supported.
4034 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
4035}
4036
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004037void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004038 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004039 const RegionCodeGenTy &CodeGen,
4040 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004041 if (!CGF.HaveInsertPoint())
4042 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004043 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004044 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004045}
4046
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004047namespace {
4048enum RTCancelKind {
4049 CancelNoreq = 0,
4050 CancelParallel = 1,
4051 CancelLoop = 2,
4052 CancelSections = 3,
4053 CancelTaskgroup = 4
4054};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004055} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004056
4057static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4058 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004059 if (CancelRegion == OMPD_parallel)
4060 CancelKind = CancelParallel;
4061 else if (CancelRegion == OMPD_for)
4062 CancelKind = CancelLoop;
4063 else if (CancelRegion == OMPD_sections)
4064 CancelKind = CancelSections;
4065 else {
4066 assert(CancelRegion == OMPD_taskgroup);
4067 CancelKind = CancelTaskgroup;
4068 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004069 return CancelKind;
4070}
4071
4072void CGOpenMPRuntime::emitCancellationPointCall(
4073 CodeGenFunction &CGF, SourceLocation Loc,
4074 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004075 if (!CGF.HaveInsertPoint())
4076 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004077 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4078 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004079 if (auto *OMPRegionInfo =
4080 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004081 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004082 llvm::Value *Args[] = {
4083 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4084 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004085 // Ignore return result until untied tasks are supported.
4086 auto *Result = CGF.EmitRuntimeCall(
4087 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4088 // if (__kmpc_cancellationpoint()) {
4089 // __kmpc_cancel_barrier();
4090 // exit from construct;
4091 // }
4092 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4093 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4094 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4095 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4096 CGF.EmitBlock(ExitBB);
4097 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004098 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004099 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004100 auto CancelDest =
4101 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004102 CGF.EmitBranchThroughCleanup(CancelDest);
4103 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4104 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004105 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004106}
4107
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004108void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004109 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004110 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004111 if (!CGF.HaveInsertPoint())
4112 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004113 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4114 // kmp_int32 cncl_kind);
4115 if (auto *OMPRegionInfo =
4116 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev424be922016-03-28 12:52:58 +00004117 RegionCodeGenTy ThenGen = [Loc, CancelRegion, OMPRegionInfo](
4118 CodeGenFunction &CGF, PrePostActionTy &) {
4119 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004120 llvm::Value *Args[] = {
Alexey Bataev424be922016-03-28 12:52:58 +00004121 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004122 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4123 // Ignore return result until untied tasks are supported.
Alexey Bataev424be922016-03-28 12:52:58 +00004124 auto *Result = CGF.EmitRuntimeCall(
4125 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004126 // if (__kmpc_cancel()) {
4127 // __kmpc_cancel_barrier();
4128 // exit from construct;
4129 // }
4130 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4131 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4132 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4133 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4134 CGF.EmitBlock(ExitBB);
4135 // __kmpc_cancel_barrier();
Alexey Bataev424be922016-03-28 12:52:58 +00004136 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004137 // exit from construct;
4138 auto CancelDest =
4139 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4140 CGF.EmitBranchThroughCleanup(CancelDest);
4141 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4142 };
4143 if (IfCond)
Alexey Bataev424be922016-03-28 12:52:58 +00004144 emitOMPIfClause(CGF, IfCond, ThenGen,
4145 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataev87933c72015-09-18 08:07:34 +00004146 else
4147 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004148 }
4149}
Samuel Antaobed3c462015-10-02 16:14:20 +00004150
Samuel Antaoee8fb302016-01-06 13:42:12 +00004151/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004152/// consists of the file and device IDs as well as line number associated with
4153/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004154static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4155 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004156 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004157
4158 auto &SM = C.getSourceManager();
4159
4160 // The loc should be always valid and have a file ID (the user cannot use
4161 // #pragma directives in macros)
4162
4163 assert(Loc.isValid() && "Source location is expected to be always valid.");
4164 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4165
4166 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4167 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4168
4169 llvm::sys::fs::UniqueID ID;
4170 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4171 llvm_unreachable("Source file with target region no longer exists!");
4172
4173 DeviceID = ID.getDevice();
4174 FileID = ID.getFile();
4175 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004176}
4177
4178void CGOpenMPRuntime::emitTargetOutlinedFunction(
4179 const OMPExecutableDirective &D, StringRef ParentName,
4180 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev424be922016-03-28 12:52:58 +00004181 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004182 assert(!ParentName.empty() && "Invalid target region parent name!");
4183
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004184 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4185 IsOffloadEntry, CodeGen);
4186}
4187
4188void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4189 const OMPExecutableDirective &D, StringRef ParentName,
4190 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4191 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004192 // Create a unique name for the entry function using the source location
4193 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004194 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004195 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004196 //
4197 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004198 // mangled name of the function that encloses the target region and BB is the
4199 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004200
4201 unsigned DeviceID;
4202 unsigned FileID;
4203 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004204 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004205 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004206 SmallString<64> EntryFnName;
4207 {
4208 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004209 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4210 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004211 }
4212
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004213 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4214
Samuel Antaobed3c462015-10-02 16:14:20 +00004215 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004216 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004217 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004218
4219 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4220
4221 // If this target outline function is not an offload entry, we don't need to
4222 // register it.
4223 if (!IsOffloadEntry)
4224 return;
4225
4226 // The target region ID is used by the runtime library to identify the current
4227 // target region, so it only has to be unique and not necessarily point to
4228 // anything. It could be the pointer to the outlined function that implements
4229 // the target region, but we aren't using that so that the compiler doesn't
4230 // need to keep that, and could therefore inline the host function if proven
4231 // worthwhile during optimization. In the other hand, if emitting code for the
4232 // device, the ID has to be the function address so that it can retrieved from
4233 // the offloading entry and launched by the runtime library. We also mark the
4234 // outlined function to have external linkage in case we are emitting code for
4235 // the device, because these functions will be entry points to the device.
4236
4237 if (CGM.getLangOpts().OpenMPIsDevice) {
4238 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4239 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4240 } else
4241 OutlinedFnID = new llvm::GlobalVariable(
4242 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4243 llvm::GlobalValue::PrivateLinkage,
4244 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4245
4246 // Register the information for the entry associated with this target region.
4247 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004248 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004249}
4250
Samuel Antaob68e2db2016-03-03 16:20:23 +00004251/// \brief Emit the num_teams clause of an enclosed teams directive at the
4252/// target region scope. If there is no teams directive associated with the
4253/// target directive, or if there is no num_teams clause associated with the
4254/// enclosed teams directive, return nullptr.
4255static llvm::Value *
4256emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4257 CodeGenFunction &CGF,
4258 const OMPExecutableDirective &D) {
4259
4260 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4261 "teams directive expected to be "
4262 "emitted only for the host!");
4263
4264 // FIXME: For the moment we do not support combined directives with target and
4265 // teams, so we do not expect to get any num_teams clause in the provided
4266 // directive. Once we support that, this assertion can be replaced by the
4267 // actual emission of the clause expression.
4268 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4269 "Not expecting clause in directive.");
4270
4271 // If the current target region has a teams region enclosed, we need to get
4272 // the number of teams to pass to the runtime function call. This is done
4273 // by generating the expression in a inlined region. This is required because
4274 // the expression is captured in the enclosing target environment when the
4275 // teams directive is not combined with target.
4276
4277 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4278
4279 // FIXME: Accommodate other combined directives with teams when they become
4280 // available.
4281 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4282 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4283 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4284 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4285 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4286 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4287 /*IsSigned=*/true);
4288 }
4289
4290 // If we have an enclosed teams directive but no num_teams clause we use
4291 // the default value 0.
4292 return CGF.Builder.getInt32(0);
4293 }
4294
4295 // No teams associated with the directive.
4296 return nullptr;
4297}
4298
4299/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4300/// target region scope. If there is no teams directive associated with the
4301/// target directive, or if there is no thread_limit clause associated with the
4302/// enclosed teams directive, return nullptr.
4303static llvm::Value *
4304emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4305 CodeGenFunction &CGF,
4306 const OMPExecutableDirective &D) {
4307
4308 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4309 "teams directive expected to be "
4310 "emitted only for the host!");
4311
4312 // FIXME: For the moment we do not support combined directives with target and
4313 // teams, so we do not expect to get any thread_limit clause in the provided
4314 // directive. Once we support that, this assertion can be replaced by the
4315 // actual emission of the clause expression.
4316 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4317 "Not expecting clause in directive.");
4318
4319 // If the current target region has a teams region enclosed, we need to get
4320 // the thread limit to pass to the runtime function call. This is done
4321 // by generating the expression in a inlined region. This is required because
4322 // the expression is captured in the enclosing target environment when the
4323 // teams directive is not combined with target.
4324
4325 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4326
4327 // FIXME: Accommodate other combined directives with teams when they become
4328 // available.
4329 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4330 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4331 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4332 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4333 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4334 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4335 /*IsSigned=*/true);
4336 }
4337
4338 // If we have an enclosed teams directive but no thread_limit clause we use
4339 // the default value 0.
4340 return CGF.Builder.getInt32(0);
4341 }
4342
4343 // No teams associated with the directive.
4344 return nullptr;
4345}
4346
Samuel Antaobed3c462015-10-02 16:14:20 +00004347void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
4348 const OMPExecutableDirective &D,
4349 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004350 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00004351 const Expr *IfCond, const Expr *Device,
4352 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004353 if (!CGF.HaveInsertPoint())
4354 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00004355 /// \brief Values for bit flags used to specify the mapping type for
4356 /// offloading.
4357 enum OpenMPOffloadMappingFlags {
4358 /// \brief Allocate memory on the device and move data from host to device.
4359 OMP_MAP_TO = 0x01,
4360 /// \brief Allocate memory on the device and move data from device to host.
4361 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004362 /// \brief The element passed to the device is a pointer.
4363 OMP_MAP_PTR = 0x20,
4364 /// \brief Pass the element to the device by value.
4365 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00004366 };
4367
4368 enum OpenMPOffloadingReservedDeviceIDs {
4369 /// \brief Device ID if the device was not defined, runtime should get it
4370 /// from environment variables in the spec.
4371 OMP_DEVICEID_UNDEF = -1,
4372 };
4373
Samuel Antaoee8fb302016-01-06 13:42:12 +00004374 assert(OutlinedFn && "Invalid outlined function!");
4375
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004376 auto &Ctx = CGF.getContext();
4377
Samuel Antaobed3c462015-10-02 16:14:20 +00004378 // Fill up the arrays with the all the captured variables.
4379 SmallVector<llvm::Value *, 16> BasePointers;
4380 SmallVector<llvm::Value *, 16> Pointers;
4381 SmallVector<llvm::Value *, 16> Sizes;
4382 SmallVector<unsigned, 16> MapTypes;
4383
4384 bool hasVLACaptures = false;
4385
4386 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4387 auto RI = CS.getCapturedRecordDecl()->field_begin();
4388 // auto II = CS.capture_init_begin();
4389 auto CV = CapturedVars.begin();
4390 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
4391 CE = CS.capture_end();
4392 CI != CE; ++CI, ++RI, ++CV) {
4393 StringRef Name;
4394 QualType Ty;
4395 llvm::Value *BasePointer;
4396 llvm::Value *Pointer;
4397 llvm::Value *Size;
4398 unsigned MapType;
4399
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004400 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00004401 if (CI->capturesVariableArrayType()) {
4402 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00004403 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004404 // Copy to the device as an argument. No need to retrieve it.
4405 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00004406 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00004407 } else if (CI->capturesThis()) {
4408 BasePointer = Pointer = *CV;
4409 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004410 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004411 // Default map type.
4412 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004413 } else if (CI->capturesVariableByCopy()) {
4414 MapType = OMP_MAP_BYCOPY;
4415 if (!RI->getType()->isAnyPointerType()) {
4416 // If the field is not a pointer, we need to save the actual value and
4417 // load it as a void pointer.
4418 auto DstAddr = CGF.CreateMemTemp(
4419 Ctx.getUIntPtrType(),
4420 Twine(CI->getCapturedVar()->getName()) + ".casted");
4421 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
4422
4423 auto *SrcAddrVal = CGF.EmitScalarConversion(
4424 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
4425 Ctx.getPointerType(RI->getType()), SourceLocation());
4426 LValue SrcLV =
4427 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
4428
4429 // Store the value using the source type pointer.
4430 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
4431
4432 // Load the value using the destination type pointer.
4433 BasePointer = Pointer =
4434 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
4435 } else {
4436 MapType |= OMP_MAP_PTR;
4437 BasePointer = Pointer = *CV;
4438 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00004439 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004440 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004441 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00004442 BasePointer = Pointer = *CV;
4443
4444 const ReferenceType *PtrTy =
4445 cast<ReferenceType>(RI->getType().getTypePtr());
4446 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004447 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004448 // The default map type for a scalar/complex type is 'to' because by
4449 // default the value doesn't have to be retrieved. For an aggregate type,
4450 // the default is 'tofrom'.
4451 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
4452 : OMP_MAP_TO;
4453 if (ElementType->isAnyPointerType())
4454 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00004455 }
4456
4457 BasePointers.push_back(BasePointer);
4458 Pointers.push_back(Pointer);
4459 Sizes.push_back(Size);
4460 MapTypes.push_back(MapType);
4461 }
4462
4463 // Keep track on whether the host function has to be executed.
4464 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004465 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004466 auto OffloadError = CGF.MakeAddrLValue(
4467 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
4468 OffloadErrorQType);
4469 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
4470 OffloadError);
4471
4472 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev424be922016-03-28 12:52:58 +00004473 RegionCodeGenTy ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
4474 hasVLACaptures, Device, OutlinedFnID, OffloadError,
4475 OffloadErrorQType,
4476 &D](CodeGenFunction &CGF, PrePostActionTy &) {
4477 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaobed3c462015-10-02 16:14:20 +00004478 unsigned PointerNumVal = BasePointers.size();
4479 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
4480 llvm::Value *BasePointersArray;
4481 llvm::Value *PointersArray;
4482 llvm::Value *SizesArray;
4483 llvm::Value *MapTypesArray;
4484
4485 if (PointerNumVal) {
4486 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004487 QualType PointerArrayType = Ctx.getConstantArrayType(
4488 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004489 /*IndexTypeQuals=*/0);
4490
4491 BasePointersArray =
4492 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
4493 PointersArray =
4494 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
4495
4496 // If we don't have any VLA types, we can use a constant array for the map
4497 // sizes, otherwise we need to fill up the arrays as we do for the
4498 // pointers.
4499 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004500 QualType SizeArrayType = Ctx.getConstantArrayType(
4501 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004502 /*IndexTypeQuals=*/0);
4503 SizesArray =
4504 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
4505 } else {
4506 // We expect all the sizes to be constant, so we collect them to create
4507 // a constant array.
4508 SmallVector<llvm::Constant *, 16> ConstSizes;
4509 for (auto S : Sizes)
4510 ConstSizes.push_back(cast<llvm::Constant>(S));
4511
4512 auto *SizesArrayInit = llvm::ConstantArray::get(
Alexey Bataev424be922016-03-28 12:52:58 +00004513 llvm::ArrayType::get(CGF.CGM.SizeTy, ConstSizes.size()),
4514 ConstSizes);
Samuel Antaobed3c462015-10-02 16:14:20 +00004515 auto *SizesArrayGbl = new llvm::GlobalVariable(
Alexey Bataev424be922016-03-28 12:52:58 +00004516 CGF.CGM.getModule(), SizesArrayInit->getType(),
Samuel Antaobed3c462015-10-02 16:14:20 +00004517 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4518 SizesArrayInit, ".offload_sizes");
4519 SizesArrayGbl->setUnnamedAddr(true);
4520 SizesArray = SizesArrayGbl;
4521 }
4522
4523 // The map types are always constant so we don't need to generate code to
4524 // fill arrays. Instead, we create an array constant.
4525 llvm::Constant *MapTypesArrayInit =
4526 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
4527 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
Alexey Bataev424be922016-03-28 12:52:58 +00004528 CGF.CGM.getModule(), MapTypesArrayInit->getType(),
Samuel Antaobed3c462015-10-02 16:14:20 +00004529 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4530 MapTypesArrayInit, ".offload_maptypes");
4531 MapTypesArrayGbl->setUnnamedAddr(true);
4532 MapTypesArray = MapTypesArrayGbl;
4533
4534 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004535 llvm::Value *BPVal = BasePointers[i];
4536 if (BPVal->getType()->isPointerTy())
Alexey Bataev424be922016-03-28 12:52:58 +00004537 BPVal = CGF.Builder.CreateBitCast(BPVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004538 else {
4539 assert(BPVal->getType()->isIntegerTy() &&
4540 "If not a pointer, the value type must be an integer.");
Alexey Bataev424be922016-03-28 12:52:58 +00004541 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004542 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004543 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev424be922016-03-28 12:52:58 +00004544 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal),
Samuel Antaobed3c462015-10-02 16:14:20 +00004545 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004546 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4547 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004548
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004549 llvm::Value *PVal = Pointers[i];
4550 if (PVal->getType()->isPointerTy())
Alexey Bataev424be922016-03-28 12:52:58 +00004551 PVal = CGF.Builder.CreateBitCast(PVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004552 else {
4553 assert(PVal->getType()->isIntegerTy() &&
4554 "If not a pointer, the value type must be an integer.");
Alexey Bataev424be922016-03-28 12:52:58 +00004555 PVal = CGF.Builder.CreateIntToPtr(PVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004556 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004557 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev424be922016-03-28 12:52:58 +00004558 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal), PointersArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00004559 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004560 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4561 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004562
4563 if (hasVLACaptures) {
4564 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev424be922016-03-28 12:52:58 +00004565 llvm::ArrayType::get(CGF.SizeTy, PointerNumVal), SizesArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00004566 /*Idx0=*/0,
4567 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004568 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004569 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
Alexey Bataev424be922016-03-28 12:52:58 +00004570 Sizes[i], CGF.SizeTy, /*isSigned=*/true),
Samuel Antaobed3c462015-10-02 16:14:20 +00004571 SAddr);
4572 }
4573 }
4574
4575 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev424be922016-03-28 12:52:58 +00004576 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal), BasePointersArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00004577 /*Idx0=*/0, /*Idx1=*/0);
4578 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev424be922016-03-28 12:52:58 +00004579 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal), PointersArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00004580 /*Idx0=*/0,
4581 /*Idx1=*/0);
4582 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev424be922016-03-28 12:52:58 +00004583 llvm::ArrayType::get(CGF.SizeTy, PointerNumVal), SizesArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00004584 /*Idx0=*/0, /*Idx1=*/0);
4585 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev424be922016-03-28 12:52:58 +00004586 llvm::ArrayType::get(CGF.Int32Ty, PointerNumVal), MapTypesArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00004587 /*Idx0=*/0,
4588 /*Idx1=*/0);
4589
4590 } else {
Alexey Bataev424be922016-03-28 12:52:58 +00004591 BasePointersArray = llvm::ConstantPointerNull::get(CGF.VoidPtrPtrTy);
4592 PointersArray = llvm::ConstantPointerNull::get(CGF.VoidPtrPtrTy);
4593 SizesArray = llvm::ConstantPointerNull::get(CGF.SizeTy->getPointerTo());
Samuel Antaobed3c462015-10-02 16:14:20 +00004594 MapTypesArray =
Alexey Bataev424be922016-03-28 12:52:58 +00004595 llvm::ConstantPointerNull::get(CGF.Int32Ty->getPointerTo());
Samuel Antaobed3c462015-10-02 16:14:20 +00004596 }
4597
4598 // On top of the arrays that were filled up, the target offloading call
4599 // takes as arguments the device id as well as the host pointer. The host
4600 // pointer is used by the runtime library to identify the current target
4601 // region, so it only has to be unique and not necessarily point to
4602 // anything. It could be the pointer to the outlined function that
4603 // implements the target region, but we aren't using that so that the
4604 // compiler doesn't need to keep that, and could therefore inline the host
4605 // function if proven worthwhile during optimization.
4606
Samuel Antaoee8fb302016-01-06 13:42:12 +00004607 // From this point on, we need to have an ID of the target region defined.
4608 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004609
4610 // Emit device ID if any.
4611 llvm::Value *DeviceID;
4612 if (Device)
4613 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev424be922016-03-28 12:52:58 +00004614 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004615 else
4616 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4617
Samuel Antaob68e2db2016-03-03 16:20:23 +00004618 // Return value of the runtime offloading call.
4619 llvm::Value *Return;
4620
Alexey Bataev424be922016-03-28 12:52:58 +00004621 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
4622 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004623
4624 // If we have NumTeams defined this means that we have an enclosed teams
4625 // region. Therefore we also expect to have ThreadLimit defined. These two
4626 // values should be defined in the presence of a teams directive, regardless
4627 // of having any clauses associated. If the user is using teams but no
4628 // clauses, these two values will be the default that should be passed to
4629 // the runtime library - a 32-bit integer with the value zero.
4630 if (NumTeams) {
4631 assert(ThreadLimit && "Thread limit expression should be available along "
4632 "with number of teams.");
4633 llvm::Value *OffloadingArgs[] = {
4634 DeviceID, OutlinedFnID, PointerNum,
4635 BasePointersArray, PointersArray, SizesArray,
4636 MapTypesArray, NumTeams, ThreadLimit};
4637 Return = CGF.EmitRuntimeCall(
Alexey Bataev424be922016-03-28 12:52:58 +00004638 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004639 } else {
4640 llvm::Value *OffloadingArgs[] = {
4641 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4642 PointersArray, SizesArray, MapTypesArray};
Alexey Bataev424be922016-03-28 12:52:58 +00004643 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00004644 OffloadingArgs);
4645 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004646
4647 CGF.EmitStoreOfScalar(Return, OffloadError);
4648 };
4649
Samuel Antaoee8fb302016-01-06 13:42:12 +00004650 // Notify that the host version must be executed.
Alexey Bataev424be922016-03-28 12:52:58 +00004651 RegionCodeGenTy ElseGen = [OffloadError](CodeGenFunction &CGF,
4652 PrePostActionTy &) {
4653 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00004654 OffloadError);
4655 };
4656
4657 // If we have a target function ID it means that we need to support
4658 // offloading, otherwise, just execute on the host. We need to execute on host
4659 // regardless of the conditional in the if clause if, e.g., the user do not
4660 // specify target triples.
4661 if (OutlinedFnID) {
Alexey Bataev424be922016-03-28 12:52:58 +00004662 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004663 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev424be922016-03-28 12:52:58 +00004664 else
Samuel Antaoee8fb302016-01-06 13:42:12 +00004665 ThenGen(CGF);
Alexey Bataev424be922016-03-28 12:52:58 +00004666 } else
Samuel Antaoee8fb302016-01-06 13:42:12 +00004667 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004668
4669 // Check the error code and execute the host version if required.
4670 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4671 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4672 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4673 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4674 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4675
4676 CGF.EmitBlock(OffloadFailedBlock);
4677 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4678 CGF.EmitBranch(OffloadContBlock);
4679
4680 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004681}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004682
4683void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4684 StringRef ParentName) {
4685 if (!S)
4686 return;
4687
4688 // If we find a OMP target directive, codegen the outline function and
4689 // register the result.
4690 // FIXME: Add other directives with target when they become supported.
4691 bool isTargetDirective = isa<OMPTargetDirective>(S);
4692
4693 if (isTargetDirective) {
4694 auto *E = cast<OMPExecutableDirective>(S);
4695 unsigned DeviceID;
4696 unsigned FileID;
4697 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004698 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004699 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004700
4701 // Is this a target region that should not be emitted as an entry point? If
4702 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00004703 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4704 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004705 return;
4706
4707 llvm::Function *Fn;
4708 llvm::Constant *Addr;
Alexey Bataev424be922016-03-28 12:52:58 +00004709 std::tie(Fn, Addr) =
4710 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
4711 CGM, cast<OMPTargetDirective>(*E), ParentName,
4712 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004713 assert(Fn && Addr && "Target region emission failed.");
4714 return;
4715 }
4716
4717 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4718 if (!E->getAssociatedStmt())
4719 return;
4720
4721 scanForTargetRegionsFunctions(
4722 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4723 ParentName);
4724 return;
4725 }
4726
4727 // If this is a lambda function, look into its body.
4728 if (auto *L = dyn_cast<LambdaExpr>(S))
4729 S = L->getBody();
4730
4731 // Keep looking for target regions recursively.
4732 for (auto *II : S->children())
4733 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004734}
4735
4736bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4737 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4738
4739 // If emitting code for the host, we do not process FD here. Instead we do
4740 // the normal code generation.
4741 if (!CGM.getLangOpts().OpenMPIsDevice)
4742 return false;
4743
4744 // Try to detect target regions in the function.
4745 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4746
4747 // We should not emit any function othen that the ones created during the
4748 // scanning. Therefore, we signal that this function is completely dealt
4749 // with.
4750 return true;
4751}
4752
4753bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4754 if (!CGM.getLangOpts().OpenMPIsDevice)
4755 return false;
4756
4757 // Check if there are Ctors/Dtors in this declaration and look for target
4758 // regions in it. We use the complete variant to produce the kernel name
4759 // mangling.
4760 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4761 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4762 for (auto *Ctor : RD->ctors()) {
4763 StringRef ParentName =
4764 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4765 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4766 }
4767 auto *Dtor = RD->getDestructor();
4768 if (Dtor) {
4769 StringRef ParentName =
4770 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4771 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4772 }
4773 }
4774
4775 // If we are in target mode we do not emit any global (declare target is not
4776 // implemented yet). Therefore we signal that GD was processed in this case.
4777 return true;
4778}
4779
4780bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4781 auto *VD = GD.getDecl();
4782 if (isa<FunctionDecl>(VD))
4783 return emitTargetFunctions(GD);
4784
4785 return emitTargetGlobalVariable(GD);
4786}
4787
4788llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4789 // If we have offloading in the current module, we need to emit the entries
4790 // now and register the offloading descriptor.
4791 createOffloadEntriesAndInfoMetadata();
4792
4793 // Create and register the offloading binary descriptors. This is the main
4794 // entity that captures all the information about offloading in the current
4795 // compilation unit.
4796 return createOffloadingBinaryDescriptorRegistration();
4797}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004798
4799void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
4800 const OMPExecutableDirective &D,
4801 SourceLocation Loc,
4802 llvm::Value *OutlinedFn,
4803 ArrayRef<llvm::Value *> CapturedVars) {
4804 if (!CGF.HaveInsertPoint())
4805 return;
4806
4807 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4808 CodeGenFunction::RunCleanupsScope Scope(CGF);
4809
4810 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
4811 llvm::Value *Args[] = {
4812 RTLoc,
4813 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
4814 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
4815 llvm::SmallVector<llvm::Value *, 16> RealArgs;
4816 RealArgs.append(std::begin(Args), std::end(Args));
4817 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
4818
4819 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
4820 CGF.EmitRuntimeCall(RTLFn, RealArgs);
4821}
4822
4823void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
4824 llvm::Value *NumTeams,
4825 llvm::Value *ThreadLimit,
4826 SourceLocation Loc) {
4827 if (!CGF.HaveInsertPoint())
4828 return;
4829
4830 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4831
4832 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
4833 llvm::Value *PushNumTeamsArgs[] = {
4834 RTLoc, getThreadID(CGF, Loc), NumTeams, ThreadLimit};
4835 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
4836 PushNumTeamsArgs);
4837}