blob: f45afaf2c899a0b9774f3d16bd76ae6654cf5ba3 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "llvm/ADT/ArrayRef.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000021#include "llvm/Bitcode/ReaderWriter.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000026#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000028#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000029
30using namespace clang;
31using namespace CodeGen;
32
Benjamin Kramerc52193f2014-10-10 13:57:57 +000033namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000035class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000037 /// \brief Kinds of OpenMP regions used in codegen.
38 enum CGOpenMPRegionKind {
39 /// \brief Region with outlined function for standalone 'parallel'
40 /// directive.
41 ParallelOutlinedRegion,
42 /// \brief Region with outlined function for standalone 'task' directive.
43 TaskOutlinedRegion,
44 /// \brief Region for constructs that do not require function outlining,
45 /// like 'for', 'sections', 'atomic' etc. directives.
46 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000047 /// \brief Region with outlined function for standalone 'target' directive.
48 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 };
Alexey Bataev18095712014-10-10 12:19:54 +000050
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 CGOpenMPRegionInfo(const CapturedStmt &CS,
52 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000055 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057
58 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000061 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000063
64 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000065 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000069 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000071 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000072 /// \return LValue for thread id variable. This LValue always has type int32*.
73 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000074
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000076
Alexey Bataev81c7ea02015-07-03 09:56:58 +000077 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
78
Alexey Bataev25e5b442015-09-15 12:52:43 +000079 bool hasCancel() const { return HasCancel; }
80
Alexey Bataev18095712014-10-10 12:19:54 +000081 static bool classof(const CGCapturedStmtInfo *Info) {
82 return Info->getKind() == CR_OpenMP;
83 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000084
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000085protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000086 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000087 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000088 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000089 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090};
Alexey Bataev18095712014-10-10 12:19:54 +000091
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092/// \brief API for captured statement code generation in OpenMP constructs.
93class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
94public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000096 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +000097 OpenMPDirectiveKind Kind, bool HasCancel)
98 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
99 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
102 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000103
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000104 /// \brief Get a variable or parameter for storing global thread id
105 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000106 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000107
Alexey Bataev18095712014-10-10 12:19:54 +0000108 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000109 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000110
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000111 static bool classof(const CGCapturedStmtInfo *Info) {
112 return CGOpenMPRegionInfo::classof(Info) &&
113 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
114 ParallelOutlinedRegion;
115 }
116
Alexey Bataev18095712014-10-10 12:19:54 +0000117private:
118 /// \brief A variable or parameter storing global thread id for OpenMP
119 /// constructs.
120 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000121};
122
Alexey Bataev62b63b12015-03-10 07:28:44 +0000123/// \brief API for captured statement code generation in OpenMP constructs.
124class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
125public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000126 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000127 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000128 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000129 OpenMPDirectiveKind Kind, bool HasCancel)
130 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000131 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
133 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000134
Alexey Bataev62b63b12015-03-10 07:28:44 +0000135 /// \brief Get a variable or parameter for storing global thread id
136 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000137 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000138
139 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000140 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000141
Alexey Bataev62b63b12015-03-10 07:28:44 +0000142 /// \brief Get the name of the capture helper.
143 StringRef getHelperName() const override { return ".omp_outlined."; }
144
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000145 static bool classof(const CGCapturedStmtInfo *Info) {
146 return CGOpenMPRegionInfo::classof(Info) &&
147 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
148 TaskOutlinedRegion;
149 }
150
Alexey Bataev62b63b12015-03-10 07:28:44 +0000151private:
152 /// \brief A variable or parameter storing global thread id for OpenMP
153 /// constructs.
154 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000155};
156
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000157/// \brief API for inlined captured statement code generation in OpenMP
158/// constructs.
159class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
160public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000161 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000162 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000163 OpenMPDirectiveKind Kind, bool HasCancel)
164 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
165 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000166 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000167
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000168 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000169 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000170 if (OuterRegionInfo)
171 return OuterRegionInfo->getContextValue();
172 llvm_unreachable("No context value for inlined OpenMP region");
173 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000174
Hans Wennborg7eb54642015-09-10 17:07:54 +0000175 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000176 if (OuterRegionInfo) {
177 OuterRegionInfo->setContextValue(V);
178 return;
179 }
180 llvm_unreachable("No context value for inlined OpenMP region");
181 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000182
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000183 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000184 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 if (OuterRegionInfo)
186 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000187 // If there is no outer outlined region,no need to lookup in a list of
188 // captured variables, we can use the original one.
189 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000190 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000191
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000193 if (OuterRegionInfo)
194 return OuterRegionInfo->getThisFieldDecl();
195 return nullptr;
196 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000197
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000198 /// \brief Get a variable or parameter for storing global thread id
199 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000200 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000201 if (OuterRegionInfo)
202 return OuterRegionInfo->getThreadIDVariable();
203 return nullptr;
204 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000205
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000206 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000207 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000208 if (auto *OuterRegionInfo = getOldCSI())
209 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000210 llvm_unreachable("No helper name for inlined OpenMP construct");
211 }
212
213 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
214
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000215 static bool classof(const CGCapturedStmtInfo *Info) {
216 return CGOpenMPRegionInfo::classof(Info) &&
217 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
218 }
219
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000220private:
221 /// \brief CodeGen info about outer OpenMP region.
222 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
223 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000224};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225
Samuel Antaobed3c462015-10-02 16:14:20 +0000226/// \brief API for captured statement code generation in OpenMP target
227/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000228/// captured fields. The name of the target region has to be unique in a given
229/// application so it is provided by the client, because only the client has
230/// the information to generate that.
Samuel Antaobed3c462015-10-02 16:14:20 +0000231class CGOpenMPTargetRegionInfo : public CGOpenMPRegionInfo {
232public:
233 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000234 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000235 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000236 /*HasCancel=*/false),
237 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000238
239 /// \brief This is unused for target regions because each starts executing
240 /// with a single thread.
241 const VarDecl *getThreadIDVariable() const override { return nullptr; }
242
243 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000244 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000245
246 static bool classof(const CGCapturedStmtInfo *Info) {
247 return CGOpenMPRegionInfo::classof(Info) &&
248 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
249 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000250
251private:
252 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000253};
254
Samuel Antaob68e2db2016-03-03 16:20:23 +0000255static void EmptyCodeGen(CodeGenFunction &) {
256 llvm_unreachable("No codegen for expressions");
257}
258/// \brief API for generation of expressions captured in a innermost OpenMP
259/// region.
260class CGOpenMPInnerExprInfo : public CGOpenMPInlinedRegionInfo {
261public:
262 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
263 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
264 OMPD_unknown,
265 /*HasCancel=*/false),
266 PrivScope(CGF) {
267 // Make sure the globals captured in the provided statement are local by
268 // using the privatization logic. We assume the same variable is not
269 // captured more than once.
270 for (auto &C : CS.captures()) {
271 if (!C.capturesVariable() && !C.capturesVariableByCopy())
272 continue;
273
274 const VarDecl *VD = C.getCapturedVar();
275 if (VD->isLocalVarDeclOrParm())
276 continue;
277
278 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
279 /*RefersToEnclosingVariableOrCapture=*/false,
280 VD->getType().getNonReferenceType(), VK_LValue,
281 SourceLocation());
282 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
283 return CGF.EmitLValue(&DRE).getAddress();
284 });
285 }
286 (void)PrivScope.Privatize();
287 }
288
289 /// \brief Lookup the captured field decl for a variable.
290 const FieldDecl *lookup(const VarDecl *VD) const override {
291 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
292 return FD;
293 return nullptr;
294 }
295
296 /// \brief Emit the captured statement body.
297 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
298 llvm_unreachable("No body for expressions");
299 }
300
301 /// \brief Get a variable or parameter for storing global thread id
302 /// inside OpenMP construct.
303 const VarDecl *getThreadIDVariable() const override {
304 llvm_unreachable("No thread id for expressions");
305 }
306
307 /// \brief Get the name of the capture helper.
308 StringRef getHelperName() const override {
309 llvm_unreachable("No helper name for expressions");
310 }
311
312 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
313
314private:
315 /// Private scope to capture global variables.
316 CodeGenFunction::OMPPrivateScope PrivScope;
317};
318
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000319/// \brief RAII for emitting code of OpenMP constructs.
320class InlinedOpenMPRegionRAII {
321 CodeGenFunction &CGF;
322
323public:
324 /// \brief Constructs region for combined constructs.
325 /// \param CodeGen Code generation sequence for combined directives. Includes
326 /// a list of functions used for code generation of implicitly inlined
327 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000328 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000329 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000330 : CGF(CGF) {
331 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000332 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
333 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000334 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000335
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000336 ~InlinedOpenMPRegionRAII() {
337 // Restore original CapturedStmtInfo only if we're done with code emission.
338 auto *OldCSI =
339 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
340 delete CGF.CapturedStmtInfo;
341 CGF.CapturedStmtInfo = OldCSI;
342 }
343};
344
Alexey Bataev50b3c952016-02-19 10:38:26 +0000345/// \brief Values for bit flags used in the ident_t to describe the fields.
346/// All enumeric elements are named and described in accordance with the code
347/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
348enum OpenMPLocationFlags {
349 /// \brief Use trampoline for internal microtask.
350 OMP_IDENT_IMD = 0x01,
351 /// \brief Use c-style ident structure.
352 OMP_IDENT_KMPC = 0x02,
353 /// \brief Atomic reduction option for kmpc_reduce.
354 OMP_ATOMIC_REDUCE = 0x10,
355 /// \brief Explicit 'barrier' directive.
356 OMP_IDENT_BARRIER_EXPL = 0x20,
357 /// \brief Implicit barrier in code.
358 OMP_IDENT_BARRIER_IMPL = 0x40,
359 /// \brief Implicit barrier in 'for' directive.
360 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
361 /// \brief Implicit barrier in 'sections' directive.
362 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
363 /// \brief Implicit barrier in 'single' directive.
364 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
365};
366
367/// \brief Describes ident structure that describes a source location.
368/// All descriptions are taken from
369/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
370/// Original structure:
371/// typedef struct ident {
372/// kmp_int32 reserved_1; /**< might be used in Fortran;
373/// see above */
374/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
375/// KMP_IDENT_KMPC identifies this union
376/// member */
377/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
378/// see above */
379///#if USE_ITT_BUILD
380/// /* but currently used for storing
381/// region-specific ITT */
382/// /* contextual information. */
383///#endif /* USE_ITT_BUILD */
384/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
385/// C++ */
386/// char const *psource; /**< String describing the source location.
387/// The string is composed of semi-colon separated
388// fields which describe the source file,
389/// the function and a pair of line numbers that
390/// delimit the construct.
391/// */
392/// } ident_t;
393enum IdentFieldIndex {
394 /// \brief might be used in Fortran
395 IdentField_Reserved_1,
396 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
397 IdentField_Flags,
398 /// \brief Not really used in Fortran any more
399 IdentField_Reserved_2,
400 /// \brief Source[4] in Fortran, do not use for C++
401 IdentField_Reserved_3,
402 /// \brief String describing the source location. The string is composed of
403 /// semi-colon separated fields which describe the source file, the function
404 /// and a pair of line numbers that delimit the construct.
405 IdentField_PSource
406};
407
408/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
409/// the enum sched_type in kmp.h).
410enum OpenMPSchedType {
411 /// \brief Lower bound for default (unordered) versions.
412 OMP_sch_lower = 32,
413 OMP_sch_static_chunked = 33,
414 OMP_sch_static = 34,
415 OMP_sch_dynamic_chunked = 35,
416 OMP_sch_guided_chunked = 36,
417 OMP_sch_runtime = 37,
418 OMP_sch_auto = 38,
419 /// \brief Lower bound for 'ordered' versions.
420 OMP_ord_lower = 64,
421 OMP_ord_static_chunked = 65,
422 OMP_ord_static = 66,
423 OMP_ord_dynamic_chunked = 67,
424 OMP_ord_guided_chunked = 68,
425 OMP_ord_runtime = 69,
426 OMP_ord_auto = 70,
427 OMP_sch_default = OMP_sch_static,
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
Hans Wennborg7eb54642015-09-10 17:07:54 +0000567} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000568
569LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000570 return CGF.EmitLoadOfPointerLValue(
571 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
572 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000573}
574
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000575void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000576 if (!CGF.HaveInsertPoint())
577 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000578 // 1.2.2 OpenMP Language Terminology
579 // Structured block - An executable statement with a single entry at the
580 // top and a single exit at the bottom.
581 // The point of exit cannot be a branch out of the structured block.
582 // longjmp() and throw() must not violate the entry/exit criteria.
583 CGF.EHStack.pushTerminate();
584 {
585 CodeGenFunction::RunCleanupsScope Scope(CGF);
586 CodeGen(CGF);
587 }
588 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000589}
590
Alexey Bataev62b63b12015-03-10 07:28:44 +0000591LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
592 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000593 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
594 getThreadIDVariable()->getType(),
595 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000596}
597
Alexey Bataev9959db52014-05-06 10:08:46 +0000598CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000599 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000600 IdentTy = llvm::StructType::create(
601 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
602 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000603 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000604 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000605 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
606 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000607 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000608 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000609
610 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000611}
612
Alexey Bataev91797552015-03-18 04:13:55 +0000613void CGOpenMPRuntime::clear() {
614 InternalVars.clear();
615}
616
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000617static llvm::Function *
618emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
619 const Expr *CombinerInitializer, const VarDecl *In,
620 const VarDecl *Out, bool IsCombiner) {
621 // void .omp_combiner.(Ty *in, Ty *out);
622 auto &C = CGM.getContext();
623 QualType PtrTy = C.getPointerType(Ty).withRestrict();
624 FunctionArgList Args;
625 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
626 /*Id=*/nullptr, PtrTy);
627 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
628 /*Id=*/nullptr, PtrTy);
629 Args.push_back(&OmpInParm);
630 Args.push_back(&OmpOutParm);
631 FunctionType::ExtInfo Info;
632 auto &FnInfo =
633 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
634 /*isVariadic=*/false);
635 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
636 auto *Fn = llvm::Function::Create(
637 FnTy, llvm::GlobalValue::InternalLinkage,
638 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
639 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
640 CodeGenFunction CGF(CGM);
641 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
642 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
643 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
644 CodeGenFunction::OMPPrivateScope Scope(CGF);
645 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
646 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
647 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
648 .getAddress();
649 });
650 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
651 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
652 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
653 .getAddress();
654 });
655 (void)Scope.Privatize();
656 CGF.EmitIgnoredExpr(CombinerInitializer);
657 Scope.ForceCleanup();
658 CGF.FinishFunction();
659 return Fn;
660}
661
662void CGOpenMPRuntime::emitUserDefinedReduction(
663 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
664 if (UDRMap.count(D) > 0)
665 return;
666 auto &C = CGM.getContext();
667 if (!In || !Out) {
668 In = &C.Idents.get("omp_in");
669 Out = &C.Idents.get("omp_out");
670 }
671 llvm::Function *Combiner = emitCombinerOrInitializer(
672 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
673 cast<VarDecl>(D->lookup(Out).front()),
674 /*IsCombiner=*/true);
675 llvm::Function *Initializer = nullptr;
676 if (auto *Init = D->getInitializer()) {
677 if (!Priv || !Orig) {
678 Priv = &C.Idents.get("omp_priv");
679 Orig = &C.Idents.get("omp_orig");
680 }
681 Initializer = emitCombinerOrInitializer(
682 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
683 cast<VarDecl>(D->lookup(Priv).front()),
684 /*IsCombiner=*/false);
685 }
686 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
687 if (CGF) {
688 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
689 Decls.second.push_back(D);
690 }
691}
692
John McCall7f416cc2015-09-08 08:05:57 +0000693// Layout information for ident_t.
694static CharUnits getIdentAlign(CodeGenModule &CGM) {
695 return CGM.getPointerAlign();
696}
697static CharUnits getIdentSize(CodeGenModule &CGM) {
698 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
699 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
700}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000701static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000702 // All the fields except the last are i32, so this works beautifully.
703 return unsigned(Field) * CharUnits::fromQuantity(4);
704}
705static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000706 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000707 const llvm::Twine &Name = "") {
708 auto Offset = getOffsetOfIdentField(Field);
709 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
710}
711
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000712llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000713 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
714 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000715 assert(ThreadIDVar->getType()->isPointerType() &&
716 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000717 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
718 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000719 bool HasCancel = false;
720 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
721 HasCancel = OPD->hasCancel();
722 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
723 HasCancel = OPSD->hasCancel();
724 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
725 HasCancel = OPFD->hasCancel();
726 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
727 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000728 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000729 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000730}
731
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000732llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
733 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
734 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000735 assert(!ThreadIDVar->getType()->isPointerType() &&
736 "thread id variable must be of type kmp_int32 for tasks");
737 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
738 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000739 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000740 InnermostKind,
741 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000742 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000743 return CGF.GenerateCapturedStmtFunction(*CS);
744}
745
Alexey Bataev50b3c952016-02-19 10:38:26 +0000746Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000747 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000748 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000749 if (!Entry) {
750 if (!DefaultOpenMPPSource) {
751 // Initialize default location for psource field of ident_t structure of
752 // all ident_t objects. Format is ";file;function;line;column;;".
753 // Taken from
754 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
755 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000756 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000757 DefaultOpenMPPSource =
758 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
759 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000760 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
761 CGM.getModule(), IdentTy, /*isConstant*/ true,
762 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000763 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000764 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000765
766 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000767 llvm::Constant *Values[] = {Zero,
768 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
769 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000770 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
771 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000772 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000773 }
John McCall7f416cc2015-09-08 08:05:57 +0000774 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000775}
776
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000777llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
778 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000779 unsigned Flags) {
780 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000781 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000782 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000783 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000784 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000785
786 assert(CGF.CurFn && "No function in current CodeGenFunction.");
787
John McCall7f416cc2015-09-08 08:05:57 +0000788 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000789 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
790 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000791 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
792
Alexander Musmanc6388682014-12-15 07:07:06 +0000793 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
794 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000795 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000796 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000797 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
798 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000799 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000800 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000801 LocValue = AI;
802
803 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
804 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000805 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000806 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000807 }
808
809 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000810 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000811
Alexey Bataevf002aca2014-05-30 05:48:40 +0000812 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
813 if (OMPDebugLoc == nullptr) {
814 SmallString<128> Buffer2;
815 llvm::raw_svector_ostream OS2(Buffer2);
816 // Build debug location
817 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
818 OS2 << ";" << PLoc.getFilename() << ";";
819 if (const FunctionDecl *FD =
820 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
821 OS2 << FD->getQualifiedNameAsString();
822 }
823 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
824 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
825 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000826 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000827 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000828 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
829
John McCall7f416cc2015-09-08 08:05:57 +0000830 // Our callers always pass this to a runtime function, so for
831 // convenience, go ahead and return a naked pointer.
832 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000833}
834
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000835llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
836 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000837 assert(CGF.CurFn && "No function in current CodeGenFunction.");
838
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000839 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000840 // Check whether we've already cached a load of the thread id in this
841 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000842 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000843 if (I != OpenMPLocThreadIDMap.end()) {
844 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000845 if (ThreadID != nullptr)
846 return ThreadID;
847 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000848 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000849 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000850 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000851 // Check if this an outlined function with thread id passed as argument.
852 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000853 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
854 // If value loaded in entry block, cache it and use it everywhere in
855 // function.
856 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
857 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
858 Elem.second.ThreadID = ThreadID;
859 }
860 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000861 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000862 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000863
864 // This is not an outlined function region - need to call __kmpc_int32
865 // kmpc_global_thread_num(ident_t *loc).
866 // Generate thread id value and cache this value for use across the
867 // function.
868 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
869 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
870 ThreadID =
871 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
872 emitUpdateLocation(CGF, Loc));
873 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
874 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000875 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000876}
877
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000878void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000879 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000880 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
881 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000882 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
883 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
884 UDRMap.erase(D);
885 }
886 FunctionUDRMap.erase(CGF.CurFn);
887 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000888}
889
890llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
891 return llvm::PointerType::getUnqual(IdentTy);
892}
893
894llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
895 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
896}
897
898llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +0000899CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000900 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +0000901 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000902 case OMPRTL__kmpc_fork_call: {
903 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
904 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000905 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
906 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000907 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000909 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
910 break;
911 }
912 case OMPRTL__kmpc_global_thread_num: {
913 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000914 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000915 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000916 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000917 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
918 break;
919 }
Alexey Bataev97720002014-11-11 04:05:39 +0000920 case OMPRTL__kmpc_threadprivate_cached: {
921 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
922 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
924 CGM.VoidPtrTy, CGM.SizeTy,
925 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
926 llvm::FunctionType *FnTy =
927 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
928 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
929 break;
930 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000931 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000932 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
933 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000934 llvm::Type *TypeParams[] = {
935 getIdentTyPointerTy(), CGM.Int32Ty,
936 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
937 llvm::FunctionType *FnTy =
938 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
939 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
940 break;
941 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000942 case OMPRTL__kmpc_critical_with_hint: {
943 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
944 // kmp_critical_name *crit, uintptr_t hint);
945 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
946 llvm::PointerType::getUnqual(KmpCriticalNameTy),
947 CGM.IntPtrTy};
948 llvm::FunctionType *FnTy =
949 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
950 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
951 break;
952 }
Alexey Bataev97720002014-11-11 04:05:39 +0000953 case OMPRTL__kmpc_threadprivate_register: {
954 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
955 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
956 // typedef void *(*kmpc_ctor)(void *);
957 auto KmpcCtorTy =
958 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
959 /*isVarArg*/ false)->getPointerTo();
960 // typedef void *(*kmpc_cctor)(void *, void *);
961 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
962 auto KmpcCopyCtorTy =
963 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
964 /*isVarArg*/ false)->getPointerTo();
965 // typedef void (*kmpc_dtor)(void *);
966 auto KmpcDtorTy =
967 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
968 ->getPointerTo();
969 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
970 KmpcCopyCtorTy, KmpcDtorTy};
971 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
972 /*isVarArg*/ false);
973 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
974 break;
975 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000976 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000977 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
978 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000979 llvm::Type *TypeParams[] = {
980 getIdentTyPointerTy(), CGM.Int32Ty,
981 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
982 llvm::FunctionType *FnTy =
983 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
984 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
985 break;
986 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000987 case OMPRTL__kmpc_cancel_barrier: {
988 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
989 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000990 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
991 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000992 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
993 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000994 break;
995 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000996 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000997 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000998 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
999 llvm::FunctionType *FnTy =
1000 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1001 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1002 break;
1003 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001004 case OMPRTL__kmpc_for_static_fini: {
1005 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1006 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1007 llvm::FunctionType *FnTy =
1008 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1009 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1010 break;
1011 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001012 case OMPRTL__kmpc_push_num_threads: {
1013 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1014 // kmp_int32 num_threads)
1015 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1016 CGM.Int32Ty};
1017 llvm::FunctionType *FnTy =
1018 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1019 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1020 break;
1021 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001022 case OMPRTL__kmpc_serialized_parallel: {
1023 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1024 // global_tid);
1025 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1026 llvm::FunctionType *FnTy =
1027 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1028 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1029 break;
1030 }
1031 case OMPRTL__kmpc_end_serialized_parallel: {
1032 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1033 // global_tid);
1034 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1035 llvm::FunctionType *FnTy =
1036 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1037 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1038 break;
1039 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001040 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001041 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001042 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1043 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001044 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001045 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1046 break;
1047 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001048 case OMPRTL__kmpc_master: {
1049 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1050 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1051 llvm::FunctionType *FnTy =
1052 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1053 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1054 break;
1055 }
1056 case OMPRTL__kmpc_end_master: {
1057 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1058 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1059 llvm::FunctionType *FnTy =
1060 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1061 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1062 break;
1063 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001064 case OMPRTL__kmpc_omp_taskyield: {
1065 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1066 // int end_part);
1067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1068 llvm::FunctionType *FnTy =
1069 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1070 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1071 break;
1072 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001073 case OMPRTL__kmpc_single: {
1074 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1075 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1076 llvm::FunctionType *FnTy =
1077 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1078 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1079 break;
1080 }
1081 case OMPRTL__kmpc_end_single: {
1082 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1083 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1084 llvm::FunctionType *FnTy =
1085 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1086 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1087 break;
1088 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001089 case OMPRTL__kmpc_omp_task_alloc: {
1090 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1091 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1092 // kmp_routine_entry_t *task_entry);
1093 assert(KmpRoutineEntryPtrTy != nullptr &&
1094 "Type kmp_routine_entry_t must be created.");
1095 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1096 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1097 // Return void * and then cast to particular kmp_task_t type.
1098 llvm::FunctionType *FnTy =
1099 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1100 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1101 break;
1102 }
1103 case OMPRTL__kmpc_omp_task: {
1104 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1105 // *new_task);
1106 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1107 CGM.VoidPtrTy};
1108 llvm::FunctionType *FnTy =
1109 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1110 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1111 break;
1112 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001113 case OMPRTL__kmpc_copyprivate: {
1114 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001115 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001116 // kmp_int32 didit);
1117 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1118 auto *CpyFnTy =
1119 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001120 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001121 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1122 CGM.Int32Ty};
1123 llvm::FunctionType *FnTy =
1124 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1125 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1126 break;
1127 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001128 case OMPRTL__kmpc_reduce: {
1129 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1130 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1131 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1132 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1133 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1134 /*isVarArg=*/false);
1135 llvm::Type *TypeParams[] = {
1136 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1137 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1138 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1139 llvm::FunctionType *FnTy =
1140 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1141 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1142 break;
1143 }
1144 case OMPRTL__kmpc_reduce_nowait: {
1145 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1146 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1147 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1148 // *lck);
1149 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1150 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1151 /*isVarArg=*/false);
1152 llvm::Type *TypeParams[] = {
1153 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1154 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1155 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1156 llvm::FunctionType *FnTy =
1157 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1158 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1159 break;
1160 }
1161 case OMPRTL__kmpc_end_reduce: {
1162 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1163 // kmp_critical_name *lck);
1164 llvm::Type *TypeParams[] = {
1165 getIdentTyPointerTy(), CGM.Int32Ty,
1166 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1167 llvm::FunctionType *FnTy =
1168 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1169 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1170 break;
1171 }
1172 case OMPRTL__kmpc_end_reduce_nowait: {
1173 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1174 // kmp_critical_name *lck);
1175 llvm::Type *TypeParams[] = {
1176 getIdentTyPointerTy(), CGM.Int32Ty,
1177 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1178 llvm::FunctionType *FnTy =
1179 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1180 RTLFn =
1181 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1182 break;
1183 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001184 case OMPRTL__kmpc_omp_task_begin_if0: {
1185 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1186 // *new_task);
1187 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1188 CGM.VoidPtrTy};
1189 llvm::FunctionType *FnTy =
1190 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1191 RTLFn =
1192 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1193 break;
1194 }
1195 case OMPRTL__kmpc_omp_task_complete_if0: {
1196 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1197 // *new_task);
1198 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1199 CGM.VoidPtrTy};
1200 llvm::FunctionType *FnTy =
1201 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1202 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1203 /*Name=*/"__kmpc_omp_task_complete_if0");
1204 break;
1205 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001206 case OMPRTL__kmpc_ordered: {
1207 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1208 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1209 llvm::FunctionType *FnTy =
1210 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1211 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1212 break;
1213 }
1214 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001215 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001216 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1217 llvm::FunctionType *FnTy =
1218 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1219 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1220 break;
1221 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001222 case OMPRTL__kmpc_omp_taskwait: {
1223 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1224 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1225 llvm::FunctionType *FnTy =
1226 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1227 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1228 break;
1229 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001230 case OMPRTL__kmpc_taskgroup: {
1231 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1232 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1233 llvm::FunctionType *FnTy =
1234 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1235 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1236 break;
1237 }
1238 case OMPRTL__kmpc_end_taskgroup: {
1239 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1240 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1241 llvm::FunctionType *FnTy =
1242 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1243 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1244 break;
1245 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001246 case OMPRTL__kmpc_push_proc_bind: {
1247 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1248 // int proc_bind)
1249 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1250 llvm::FunctionType *FnTy =
1251 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1252 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1253 break;
1254 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001255 case OMPRTL__kmpc_omp_task_with_deps: {
1256 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1257 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1258 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1259 llvm::Type *TypeParams[] = {
1260 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1261 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1262 llvm::FunctionType *FnTy =
1263 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1264 RTLFn =
1265 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1266 break;
1267 }
1268 case OMPRTL__kmpc_omp_wait_deps: {
1269 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1270 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1271 // kmp_depend_info_t *noalias_dep_list);
1272 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1273 CGM.Int32Ty, CGM.VoidPtrTy,
1274 CGM.Int32Ty, CGM.VoidPtrTy};
1275 llvm::FunctionType *FnTy =
1276 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1277 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1278 break;
1279 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001280 case OMPRTL__kmpc_cancellationpoint: {
1281 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1282 // global_tid, kmp_int32 cncl_kind)
1283 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1284 llvm::FunctionType *FnTy =
1285 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1286 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1287 break;
1288 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001289 case OMPRTL__kmpc_cancel: {
1290 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1291 // kmp_int32 cncl_kind)
1292 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1293 llvm::FunctionType *FnTy =
1294 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1295 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1296 break;
1297 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001298 case OMPRTL__kmpc_push_num_teams: {
1299 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1300 // kmp_int32 num_teams, kmp_int32 num_threads)
1301 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1302 CGM.Int32Ty};
1303 llvm::FunctionType *FnTy =
1304 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1305 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1306 break;
1307 }
1308 case OMPRTL__kmpc_fork_teams: {
1309 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1310 // microtask, ...);
1311 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1312 getKmpc_MicroPointerTy()};
1313 llvm::FunctionType *FnTy =
1314 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1315 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1316 break;
1317 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001318 case OMPRTL__tgt_target: {
1319 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1320 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1321 // *arg_types);
1322 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1323 CGM.VoidPtrTy,
1324 CGM.Int32Ty,
1325 CGM.VoidPtrPtrTy,
1326 CGM.VoidPtrPtrTy,
1327 CGM.SizeTy->getPointerTo(),
1328 CGM.Int32Ty->getPointerTo()};
1329 llvm::FunctionType *FnTy =
1330 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1331 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1332 break;
1333 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001334 case OMPRTL__tgt_target_teams: {
1335 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1336 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1337 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1338 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1339 CGM.VoidPtrTy,
1340 CGM.Int32Ty,
1341 CGM.VoidPtrPtrTy,
1342 CGM.VoidPtrPtrTy,
1343 CGM.SizeTy->getPointerTo(),
1344 CGM.Int32Ty->getPointerTo(),
1345 CGM.Int32Ty,
1346 CGM.Int32Ty};
1347 llvm::FunctionType *FnTy =
1348 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1349 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1350 break;
1351 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001352 case OMPRTL__tgt_register_lib: {
1353 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1354 QualType ParamTy =
1355 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1356 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1357 llvm::FunctionType *FnTy =
1358 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1359 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1360 break;
1361 }
1362 case OMPRTL__tgt_unregister_lib: {
1363 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1364 QualType ParamTy =
1365 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1366 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1367 llvm::FunctionType *FnTy =
1368 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1369 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1370 break;
1371 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001372 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001373 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001374 return RTLFn;
1375}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001376
Alexander Musman21212e42015-03-13 10:38:23 +00001377llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1378 bool IVSigned) {
1379 assert((IVSize == 32 || IVSize == 64) &&
1380 "IV size is not compatible with the omp runtime");
1381 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1382 : "__kmpc_for_static_init_4u")
1383 : (IVSigned ? "__kmpc_for_static_init_8"
1384 : "__kmpc_for_static_init_8u");
1385 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1386 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1387 llvm::Type *TypeParams[] = {
1388 getIdentTyPointerTy(), // loc
1389 CGM.Int32Ty, // tid
1390 CGM.Int32Ty, // schedtype
1391 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1392 PtrTy, // p_lower
1393 PtrTy, // p_upper
1394 PtrTy, // p_stride
1395 ITy, // incr
1396 ITy // chunk
1397 };
1398 llvm::FunctionType *FnTy =
1399 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1400 return CGM.CreateRuntimeFunction(FnTy, Name);
1401}
1402
Alexander Musman92bdaab2015-03-12 13:37:50 +00001403llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1404 bool IVSigned) {
1405 assert((IVSize == 32 || IVSize == 64) &&
1406 "IV size is not compatible with the omp runtime");
1407 auto Name =
1408 IVSize == 32
1409 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1410 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1411 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1412 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1413 CGM.Int32Ty, // tid
1414 CGM.Int32Ty, // schedtype
1415 ITy, // lower
1416 ITy, // upper
1417 ITy, // stride
1418 ITy // chunk
1419 };
1420 llvm::FunctionType *FnTy =
1421 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1422 return CGM.CreateRuntimeFunction(FnTy, Name);
1423}
1424
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001425llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1426 bool IVSigned) {
1427 assert((IVSize == 32 || IVSize == 64) &&
1428 "IV size is not compatible with the omp runtime");
1429 auto Name =
1430 IVSize == 32
1431 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1432 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1433 llvm::Type *TypeParams[] = {
1434 getIdentTyPointerTy(), // loc
1435 CGM.Int32Ty, // tid
1436 };
1437 llvm::FunctionType *FnTy =
1438 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1439 return CGM.CreateRuntimeFunction(FnTy, Name);
1440}
1441
Alexander Musman92bdaab2015-03-12 13:37:50 +00001442llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1443 bool IVSigned) {
1444 assert((IVSize == 32 || IVSize == 64) &&
1445 "IV size is not compatible with the omp runtime");
1446 auto Name =
1447 IVSize == 32
1448 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1449 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1450 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1451 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1452 llvm::Type *TypeParams[] = {
1453 getIdentTyPointerTy(), // loc
1454 CGM.Int32Ty, // tid
1455 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1456 PtrTy, // p_lower
1457 PtrTy, // p_upper
1458 PtrTy // p_stride
1459 };
1460 llvm::FunctionType *FnTy =
1461 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1462 return CGM.CreateRuntimeFunction(FnTy, Name);
1463}
1464
Alexey Bataev97720002014-11-11 04:05:39 +00001465llvm::Constant *
1466CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001467 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1468 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001469 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001470 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001471 Twine(CGM.getMangledName(VD)) + ".cache.");
1472}
1473
John McCall7f416cc2015-09-08 08:05:57 +00001474Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1475 const VarDecl *VD,
1476 Address VDAddr,
1477 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001478 if (CGM.getLangOpts().OpenMPUseTLS &&
1479 CGM.getContext().getTargetInfo().isTLSSupported())
1480 return VDAddr;
1481
John McCall7f416cc2015-09-08 08:05:57 +00001482 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001483 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001484 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1485 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001486 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1487 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001488 return Address(CGF.EmitRuntimeCall(
1489 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1490 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001491}
1492
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001493void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001494 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001495 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1496 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1497 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001498 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1499 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001500 OMPLoc);
1501 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1502 // to register constructor/destructor for variable.
1503 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001504 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1505 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001506 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001507 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001508 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001509}
1510
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001511llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001512 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001513 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001514 if (CGM.getLangOpts().OpenMPUseTLS &&
1515 CGM.getContext().getTargetInfo().isTLSSupported())
1516 return nullptr;
1517
Alexey Bataev97720002014-11-11 04:05:39 +00001518 VD = VD->getDefinition(CGM.getContext());
1519 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1520 ThreadPrivateWithDefinition.insert(VD);
1521 QualType ASTTy = VD->getType();
1522
1523 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1524 auto Init = VD->getAnyInitializer();
1525 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1526 // Generate function that re-emits the declaration's initializer into the
1527 // threadprivate copy of the variable VD
1528 CodeGenFunction CtorCGF(CGM);
1529 FunctionArgList Args;
1530 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1531 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1532 Args.push_back(&Dst);
1533
1534 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1535 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1536 /*isVariadic=*/false);
1537 auto FTy = CGM.getTypes().GetFunctionType(FI);
1538 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001539 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001540 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1541 Args, SourceLocation());
1542 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001543 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001544 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001545 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1546 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1547 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001548 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1549 /*IsInitializer=*/true);
1550 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001551 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001552 CGM.getContext().VoidPtrTy, Dst.getLocation());
1553 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1554 CtorCGF.FinishFunction();
1555 Ctor = Fn;
1556 }
1557 if (VD->getType().isDestructedType() != QualType::DK_none) {
1558 // Generate function that emits destructor call for the threadprivate copy
1559 // of the variable VD
1560 CodeGenFunction DtorCGF(CGM);
1561 FunctionArgList Args;
1562 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1563 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1564 Args.push_back(&Dst);
1565
1566 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1567 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1568 /*isVariadic=*/false);
1569 auto FTy = CGM.getTypes().GetFunctionType(FI);
1570 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001571 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001572 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1573 SourceLocation());
1574 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1575 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001576 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1577 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001578 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1579 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1580 DtorCGF.FinishFunction();
1581 Dtor = Fn;
1582 }
1583 // Do not emit init function if it is not required.
1584 if (!Ctor && !Dtor)
1585 return nullptr;
1586
1587 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1588 auto CopyCtorTy =
1589 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1590 /*isVarArg=*/false)->getPointerTo();
1591 // Copying constructor for the threadprivate variable.
1592 // Must be NULL - reserved by runtime, but currently it requires that this
1593 // parameter is always NULL. Otherwise it fires assertion.
1594 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1595 if (Ctor == nullptr) {
1596 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1597 /*isVarArg=*/false)->getPointerTo();
1598 Ctor = llvm::Constant::getNullValue(CtorTy);
1599 }
1600 if (Dtor == nullptr) {
1601 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1602 /*isVarArg=*/false)->getPointerTo();
1603 Dtor = llvm::Constant::getNullValue(DtorTy);
1604 }
1605 if (!CGF) {
1606 auto InitFunctionTy =
1607 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1608 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001609 InitFunctionTy, ".__omp_threadprivate_init_.",
1610 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001611 CodeGenFunction InitCGF(CGM);
1612 FunctionArgList ArgList;
1613 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1614 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1615 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001616 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001617 InitCGF.FinishFunction();
1618 return InitFunction;
1619 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001620 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001621 }
1622 return nullptr;
1623}
1624
Alexey Bataev1d677132015-04-22 13:57:31 +00001625/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1626/// function. Here is the logic:
1627/// if (Cond) {
1628/// ThenGen();
1629/// } else {
1630/// ElseGen();
1631/// }
1632static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1633 const RegionCodeGenTy &ThenGen,
1634 const RegionCodeGenTy &ElseGen) {
1635 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1636
1637 // If the condition constant folds and can be elided, try to avoid emitting
1638 // the condition and the dead arm of the if/else.
1639 bool CondConstant;
1640 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1641 CodeGenFunction::RunCleanupsScope Scope(CGF);
1642 if (CondConstant) {
1643 ThenGen(CGF);
1644 } else {
1645 ElseGen(CGF);
1646 }
1647 return;
1648 }
1649
1650 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1651 // emit the conditional branch.
1652 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1653 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1654 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1655 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1656
1657 // Emit the 'then' code.
1658 CGF.EmitBlock(ThenBlock);
1659 {
1660 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1661 ThenGen(CGF);
1662 }
1663 CGF.EmitBranch(ContBlock);
1664 // Emit the 'else' code if present.
1665 {
1666 // There is no need to emit line number for unconditional branch.
1667 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1668 CGF.EmitBlock(ElseBlock);
1669 }
1670 {
1671 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1672 ElseGen(CGF);
1673 }
1674 {
1675 // There is no need to emit line number for unconditional branch.
1676 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1677 CGF.EmitBranch(ContBlock);
1678 }
1679 // Emit the continuation block for code after the if.
1680 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001681}
1682
Alexey Bataev1d677132015-04-22 13:57:31 +00001683void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1684 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001685 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001686 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001687 if (!CGF.HaveInsertPoint())
1688 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001689 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001690 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1691 RTLoc](CodeGenFunction &CGF) {
1692 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1693 llvm::Value *Args[] = {
1694 RTLoc,
1695 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1696 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1697 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1698 RealArgs.append(std::begin(Args), std::end(Args));
1699 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1700
1701 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1702 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1703 };
1704 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1705 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001706 auto ThreadID = getThreadID(CGF, Loc);
1707 // Build calls:
1708 // __kmpc_serialized_parallel(&Loc, GTid);
1709 llvm::Value *Args[] = {RTLoc, ThreadID};
1710 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1711 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001712
Alexey Bataev1d677132015-04-22 13:57:31 +00001713 // OutlinedFn(&GTid, &zero, CapturedStruct);
1714 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001715 Address ZeroAddr =
1716 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1717 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001718 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001719 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1720 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1721 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1722 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001723 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001724
Alexey Bataev1d677132015-04-22 13:57:31 +00001725 // __kmpc_end_serialized_parallel(&Loc, GTid);
1726 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1727 CGF.EmitRuntimeCall(
1728 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1729 };
1730 if (IfCond) {
1731 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1732 } else {
1733 CodeGenFunction::RunCleanupsScope Scope(CGF);
1734 ThenGen(CGF);
1735 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001736}
1737
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001738// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001739// thread-ID variable (it is passed in a first argument of the outlined function
1740// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1741// regular serial code region, get thread ID by calling kmp_int32
1742// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1743// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001744Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1745 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001746 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001747 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001748 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001749 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001750
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001751 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001752 auto Int32Ty =
1753 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1754 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1755 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001756 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001757
1758 return ThreadIDTemp;
1759}
1760
Alexey Bataev97720002014-11-11 04:05:39 +00001761llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001762CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001763 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001764 SmallString<256> Buffer;
1765 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001766 Out << Name;
1767 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001768 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1769 if (Elem.second) {
1770 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001771 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001772 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001773 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001774
David Blaikie13156b62014-11-19 03:06:06 +00001775 return Elem.second = new llvm::GlobalVariable(
1776 CGM.getModule(), Ty, /*IsConstant*/ false,
1777 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1778 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001779}
1780
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001781llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001782 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001783 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001784}
1785
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001786namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001787template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001788 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001789 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001790
1791public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001792 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1793 : Callee(Callee) {
1794 assert(CleanupArgs.size() == N);
1795 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1796 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001797
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001798 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001799 if (!CGF.HaveInsertPoint())
1800 return;
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001801 CGF.EmitRuntimeCall(Callee, Args);
1802 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001803};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001804} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001805
1806void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1807 StringRef CriticalName,
1808 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001809 SourceLocation Loc, const Expr *Hint) {
1810 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001811 // CriticalOpGen();
1812 // __kmpc_end_critical(ident_t *, gtid, Lock);
1813 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001814 if (!CGF.HaveInsertPoint())
1815 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001816 CodeGenFunction::RunCleanupsScope Scope(CGF);
1817 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1818 getCriticalRegionLock(CriticalName)};
1819 if (Hint) {
1820 llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1821 std::end(Args));
1822 auto *HintVal = CGF.EmitScalarExpr(Hint);
1823 ArgsWithHint.push_back(
1824 CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1825 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1826 ArgsWithHint);
1827 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001828 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001829 // Build a call to __kmpc_end_critical
1830 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1831 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1832 llvm::makeArrayRef(Args));
1833 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001834}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001835
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001836static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001837 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001838 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001839 llvm::Value *CallBool = CGF.EmitScalarConversion(
1840 IfCond,
1841 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001842 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001843
1844 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1845 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1846 // Generate the branch (If-stmt)
1847 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1848 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001849 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001850 // Emit the rest of bblocks/branches
1851 CGF.EmitBranch(ContBlock);
1852 CGF.EmitBlock(ContBlock, true);
1853}
1854
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001855void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001856 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001857 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001858 if (!CGF.HaveInsertPoint())
1859 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001860 // if(__kmpc_master(ident_t *, gtid)) {
1861 // MasterOpGen();
1862 // __kmpc_end_master(ident_t *, gtid);
1863 // }
1864 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001865 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001866 auto *IsMaster =
1867 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001868 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1869 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001870 emitIfStmt(
1871 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1872 CodeGenFunction::RunCleanupsScope Scope(CGF);
1873 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1874 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1875 llvm::makeArrayRef(Args));
1876 MasterOpGen(CGF);
1877 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001878}
1879
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001880void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1881 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001882 if (!CGF.HaveInsertPoint())
1883 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001884 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1885 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001886 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001887 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001888 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001889}
1890
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001891void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1892 const RegionCodeGenTy &TaskgroupOpGen,
1893 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001894 if (!CGF.HaveInsertPoint())
1895 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001896 // __kmpc_taskgroup(ident_t *, gtid);
1897 // TaskgroupOpGen();
1898 // __kmpc_end_taskgroup(ident_t *, gtid);
1899 // Prepare arguments and build a call to __kmpc_taskgroup
1900 {
1901 CodeGenFunction::RunCleanupsScope Scope(CGF);
1902 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1903 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1904 // Build a call to __kmpc_end_taskgroup
1905 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1906 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1907 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001908 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001909 }
1910}
1911
John McCall7f416cc2015-09-08 08:05:57 +00001912/// Given an array of pointers to variables, project the address of a
1913/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001914static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1915 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001916 // Pull out the pointer to the variable.
1917 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001918 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001919 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1920
1921 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001922 Addr = CGF.Builder.CreateElementBitCast(
1923 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001924 return Addr;
1925}
1926
Alexey Bataeva63048e2015-03-23 06:18:07 +00001927static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001928 CodeGenModule &CGM, llvm::Type *ArgsType,
1929 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1930 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001931 auto &C = CGM.getContext();
1932 // void copy_func(void *LHSArg, void *RHSArg);
1933 FunctionArgList Args;
1934 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1935 C.VoidPtrTy);
1936 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1937 C.VoidPtrTy);
1938 Args.push_back(&LHSArg);
1939 Args.push_back(&RHSArg);
1940 FunctionType::ExtInfo EI;
1941 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1942 C.VoidTy, Args, EI, /*isVariadic=*/false);
1943 auto *Fn = llvm::Function::Create(
1944 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1945 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001946 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001947 CodeGenFunction CGF(CGM);
1948 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001949 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001950 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001951 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1952 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1953 ArgsType), CGF.getPointerAlign());
1954 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1955 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1956 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001957 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1958 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1959 // ...
1960 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001961 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001962 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1963 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1964
1965 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1966 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1967
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001968 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1969 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001970 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001971 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001972 CGF.FinishFunction();
1973 return Fn;
1974}
1975
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001976void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001977 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001978 SourceLocation Loc,
1979 ArrayRef<const Expr *> CopyprivateVars,
1980 ArrayRef<const Expr *> SrcExprs,
1981 ArrayRef<const Expr *> DstExprs,
1982 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001983 if (!CGF.HaveInsertPoint())
1984 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001985 assert(CopyprivateVars.size() == SrcExprs.size() &&
1986 CopyprivateVars.size() == DstExprs.size() &&
1987 CopyprivateVars.size() == AssignmentOps.size());
1988 auto &C = CGM.getContext();
1989 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001990 // if(__kmpc_single(ident_t *, gtid)) {
1991 // SingleOpGen();
1992 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001993 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001994 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001995 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1996 // <copy_func>, did_it);
1997
John McCall7f416cc2015-09-08 08:05:57 +00001998 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001999 if (!CopyprivateVars.empty()) {
2000 // int32 did_it = 0;
2001 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2002 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002003 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002004 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002005 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002006 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002007 auto *IsSingle =
2008 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00002009 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
2010 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002011 emitIfStmt(
2012 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
2013 CodeGenFunction::RunCleanupsScope Scope(CGF);
2014 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
2015 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
2016 llvm::makeArrayRef(Args));
2017 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002018 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002019 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00002020 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002021 }
2022 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00002023 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2024 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002025 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002026 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2027 auto CopyprivateArrayTy =
2028 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2029 /*IndexTypeQuals=*/0);
2030 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002031 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002032 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2033 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002034 Address Elem = CGF.Builder.CreateConstArrayGEP(
2035 CopyprivateList, I, CGF.getPointerSize());
2036 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002037 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002038 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2039 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002040 }
2041 // Build function that copies private values from single region to all other
2042 // threads in the corresponding parallel region.
2043 auto *CpyFn = emitCopyprivateCopyFunction(
2044 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002045 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002046 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002047 Address CL =
2048 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2049 CGF.VoidPtrTy);
2050 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002051 llvm::Value *Args[] = {
2052 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2053 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002054 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002055 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002056 CpyFn, // void (*) (void *, void *) <copy_func>
2057 DidItVal // i32 did_it
2058 };
2059 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2060 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002061}
2062
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002063void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2064 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002065 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002066 if (!CGF.HaveInsertPoint())
2067 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002068 // __kmpc_ordered(ident_t *, gtid);
2069 // OrderedOpGen();
2070 // __kmpc_end_ordered(ident_t *, gtid);
2071 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002072 CodeGenFunction::RunCleanupsScope Scope(CGF);
2073 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002074 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2075 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
2076 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00002077 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002078 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2079 llvm::makeArrayRef(Args));
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002080 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002081 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002082}
2083
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002084void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002085 OpenMPDirectiveKind Kind, bool EmitChecks,
2086 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002087 if (!CGF.HaveInsertPoint())
2088 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002089 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002090 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002091 unsigned Flags;
2092 if (Kind == OMPD_for)
2093 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2094 else if (Kind == OMPD_sections)
2095 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2096 else if (Kind == OMPD_single)
2097 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2098 else if (Kind == OMPD_barrier)
2099 Flags = OMP_IDENT_BARRIER_EXPL;
2100 else
2101 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002102 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2103 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002104 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2105 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002106 if (auto *OMPRegionInfo =
2107 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002108 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002109 auto *Result = CGF.EmitRuntimeCall(
2110 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002111 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002112 // if (__kmpc_cancel_barrier()) {
2113 // exit from construct;
2114 // }
2115 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2116 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2117 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2118 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2119 CGF.EmitBlock(ExitBB);
2120 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002121 auto CancelDestination =
2122 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002123 CGF.EmitBranchThroughCleanup(CancelDestination);
2124 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2125 }
2126 return;
2127 }
2128 }
2129 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002130}
2131
Alexander Musmanc6388682014-12-15 07:07:06 +00002132/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2133static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002134 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002135 switch (ScheduleKind) {
2136 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002137 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2138 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002139 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002140 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002141 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002142 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002143 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002144 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2145 case OMPC_SCHEDULE_auto:
2146 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002147 case OMPC_SCHEDULE_unknown:
2148 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002149 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002150 }
2151 llvm_unreachable("Unexpected runtime schedule");
2152}
2153
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002154/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2155static OpenMPSchedType
2156getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2157 // only static is allowed for dist_schedule
2158 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2159}
2160
Alexander Musmanc6388682014-12-15 07:07:06 +00002161bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2162 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002163 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002164 return Schedule == OMP_sch_static;
2165}
2166
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002167bool CGOpenMPRuntime::isStaticNonchunked(
2168 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2169 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2170 return Schedule == OMP_dist_sch_static;
2171}
2172
2173
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002174bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002175 auto Schedule =
2176 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002177 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2178 return Schedule != OMP_sch_static;
2179}
2180
John McCall7f416cc2015-09-08 08:05:57 +00002181void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2182 SourceLocation Loc,
2183 OpenMPScheduleClauseKind ScheduleKind,
2184 unsigned IVSize, bool IVSigned,
2185 bool Ordered, llvm::Value *UB,
2186 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002187 if (!CGF.HaveInsertPoint())
2188 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002189 OpenMPSchedType Schedule =
2190 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002191 assert(Ordered ||
2192 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2193 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2194 // Call __kmpc_dispatch_init(
2195 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2196 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2197 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002198
John McCall7f416cc2015-09-08 08:05:57 +00002199 // If the Chunk was not specified in the clause - use default value 1.
2200 if (Chunk == nullptr)
2201 Chunk = CGF.Builder.getIntN(IVSize, 1);
2202 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002203 emitUpdateLocation(CGF, Loc),
2204 getThreadID(CGF, Loc),
2205 CGF.Builder.getInt32(Schedule), // Schedule type
2206 CGF.Builder.getIntN(IVSize, 0), // Lower
2207 UB, // Upper
2208 CGF.Builder.getIntN(IVSize, 1), // Stride
2209 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002210 };
2211 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2212}
2213
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002214static void emitForStaticInitCall(CodeGenFunction &CGF,
2215 SourceLocation Loc,
2216 llvm::Value * UpdateLocation,
2217 llvm::Value * ThreadId,
2218 llvm::Constant * ForStaticInitFunction,
2219 OpenMPSchedType Schedule,
2220 unsigned IVSize, bool IVSigned, bool Ordered,
2221 Address IL, Address LB, Address UB,
2222 Address ST, llvm::Value *Chunk) {
2223 if (!CGF.HaveInsertPoint())
2224 return;
2225
2226 assert(!Ordered);
2227 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2228 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2229 Schedule == OMP_dist_sch_static ||
2230 Schedule == OMP_dist_sch_static_chunked);
2231
2232 // Call __kmpc_for_static_init(
2233 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2234 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2235 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2236 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2237 if (Chunk == nullptr) {
2238 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2239 Schedule == OMP_dist_sch_static) &&
2240 "expected static non-chunked schedule");
2241 // If the Chunk was not specified in the clause - use default value 1.
2242 Chunk = CGF.Builder.getIntN(IVSize, 1);
2243 } else {
2244 assert((Schedule == OMP_sch_static_chunked ||
2245 Schedule == OMP_ord_static_chunked ||
2246 Schedule == OMP_dist_sch_static_chunked) &&
2247 "expected static chunked schedule");
2248 }
2249 llvm::Value *Args[] = {
2250 UpdateLocation,
2251 ThreadId,
2252 CGF.Builder.getInt32(Schedule), // Schedule type
2253 IL.getPointer(), // &isLastIter
2254 LB.getPointer(), // &LB
2255 UB.getPointer(), // &UB
2256 ST.getPointer(), // &Stride
2257 CGF.Builder.getIntN(IVSize, 1), // Incr
2258 Chunk // Chunk
2259 };
2260 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2261}
2262
John McCall7f416cc2015-09-08 08:05:57 +00002263void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2264 SourceLocation Loc,
2265 OpenMPScheduleClauseKind ScheduleKind,
2266 unsigned IVSize, bool IVSigned,
2267 bool Ordered, Address IL, Address LB,
2268 Address UB, Address ST,
2269 llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002270 OpenMPSchedType ScheduleNum = getRuntimeSchedule(ScheduleKind, Chunk != nullptr,
2271 Ordered);
2272 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2273 auto *ThreadId = getThreadID(CGF, Loc);
2274 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2275 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2276 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
2277}
John McCall7f416cc2015-09-08 08:05:57 +00002278
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002279void CGOpenMPRuntime::emitDistributeStaticInit(CodeGenFunction &CGF,
2280 SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind,
2281 unsigned IVSize, bool IVSigned,
2282 bool Ordered, Address IL, Address LB,
2283 Address UB, Address ST,
2284 llvm::Value *Chunk) {
2285 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2286 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2287 auto *ThreadId = getThreadID(CGF, Loc);
2288 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2289 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2290 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002291}
2292
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002293void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2294 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002295 if (!CGF.HaveInsertPoint())
2296 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002297 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002298 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002299 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2300 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002301}
2302
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002303void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2304 SourceLocation Loc,
2305 unsigned IVSize,
2306 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002307 if (!CGF.HaveInsertPoint())
2308 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002309 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002310 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002311 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2312}
2313
Alexander Musman92bdaab2015-03-12 13:37:50 +00002314llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2315 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002316 bool IVSigned, Address IL,
2317 Address LB, Address UB,
2318 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002319 // Call __kmpc_dispatch_next(
2320 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2321 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2322 // kmp_int[32|64] *p_stride);
2323 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002324 emitUpdateLocation(CGF, Loc),
2325 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002326 IL.getPointer(), // &isLastIter
2327 LB.getPointer(), // &Lower
2328 UB.getPointer(), // &Upper
2329 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002330 };
2331 llvm::Value *Call =
2332 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2333 return CGF.EmitScalarConversion(
2334 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002335 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002336}
2337
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002338void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2339 llvm::Value *NumThreads,
2340 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002341 if (!CGF.HaveInsertPoint())
2342 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002343 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2344 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002345 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002346 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002347 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2348 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002349}
2350
Alexey Bataev7f210c62015-06-18 13:40:03 +00002351void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2352 OpenMPProcBindClauseKind ProcBind,
2353 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002354 if (!CGF.HaveInsertPoint())
2355 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002356 // Constants for proc bind value accepted by the runtime.
2357 enum ProcBindTy {
2358 ProcBindFalse = 0,
2359 ProcBindTrue,
2360 ProcBindMaster,
2361 ProcBindClose,
2362 ProcBindSpread,
2363 ProcBindIntel,
2364 ProcBindDefault
2365 } RuntimeProcBind;
2366 switch (ProcBind) {
2367 case OMPC_PROC_BIND_master:
2368 RuntimeProcBind = ProcBindMaster;
2369 break;
2370 case OMPC_PROC_BIND_close:
2371 RuntimeProcBind = ProcBindClose;
2372 break;
2373 case OMPC_PROC_BIND_spread:
2374 RuntimeProcBind = ProcBindSpread;
2375 break;
2376 case OMPC_PROC_BIND_unknown:
2377 llvm_unreachable("Unsupported proc_bind value.");
2378 }
2379 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2380 llvm::Value *Args[] = {
2381 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2382 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2383 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2384}
2385
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002386void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2387 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002388 if (!CGF.HaveInsertPoint())
2389 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002390 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002391 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2392 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002393}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002394
Alexey Bataev62b63b12015-03-10 07:28:44 +00002395namespace {
2396/// \brief Indexes of fields for type kmp_task_t.
2397enum KmpTaskTFields {
2398 /// \brief List of shared variables.
2399 KmpTaskTShareds,
2400 /// \brief Task routine.
2401 KmpTaskTRoutine,
2402 /// \brief Partition id for the untied tasks.
2403 KmpTaskTPartId,
2404 /// \brief Function with call of destructors for private variables.
2405 KmpTaskTDestructors,
2406};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002407} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002408
Samuel Antaoee8fb302016-01-06 13:42:12 +00002409bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2410 // FIXME: Add other entries type when they become supported.
2411 return OffloadEntriesTargetRegion.empty();
2412}
2413
2414/// \brief Initialize target region entry.
2415void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2416 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2417 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002418 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002419 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2420 "only required for the device "
2421 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002422 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002423 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2424 ++OffloadingEntriesNum;
2425}
2426
2427void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2428 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2429 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002430 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002431 // If we are emitting code for a target, the entry is already initialized,
2432 // only has to be registered.
2433 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002434 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002435 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002436 auto &Entry =
2437 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002438 assert(Entry.isValid() && "Entry not initialized!");
2439 Entry.setAddress(Addr);
2440 Entry.setID(ID);
2441 return;
2442 } else {
2443 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002444 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002445 }
2446}
2447
2448bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002449 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2450 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002451 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2452 if (PerDevice == OffloadEntriesTargetRegion.end())
2453 return false;
2454 auto PerFile = PerDevice->second.find(FileID);
2455 if (PerFile == PerDevice->second.end())
2456 return false;
2457 auto PerParentName = PerFile->second.find(ParentName);
2458 if (PerParentName == PerFile->second.end())
2459 return false;
2460 auto PerLine = PerParentName->second.find(LineNum);
2461 if (PerLine == PerParentName->second.end())
2462 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002463 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002464 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002465 return false;
2466 return true;
2467}
2468
2469void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2470 const OffloadTargetRegionEntryInfoActTy &Action) {
2471 // Scan all target region entries and perform the provided action.
2472 for (auto &D : OffloadEntriesTargetRegion)
2473 for (auto &F : D.second)
2474 for (auto &P : F.second)
2475 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002476 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002477}
2478
2479/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2480/// \a Codegen. This is used to emit the two functions that register and
2481/// unregister the descriptor of the current compilation unit.
2482static llvm::Function *
2483createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2484 const RegionCodeGenTy &Codegen) {
2485 auto &C = CGM.getContext();
2486 FunctionArgList Args;
2487 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2488 /*Id=*/nullptr, C.VoidPtrTy);
2489 Args.push_back(&DummyPtr);
2490
2491 CodeGenFunction CGF(CGM);
2492 GlobalDecl();
2493 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2494 C.VoidTy, Args, FunctionType::ExtInfo(),
2495 /*isVariadic=*/false);
2496 auto FTy = CGM.getTypes().GetFunctionType(FI);
2497 auto *Fn =
2498 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2499 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2500 Codegen(CGF);
2501 CGF.FinishFunction();
2502 return Fn;
2503}
2504
2505llvm::Function *
2506CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2507
2508 // If we don't have entries or if we are emitting code for the device, we
2509 // don't need to do anything.
2510 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2511 return nullptr;
2512
2513 auto &M = CGM.getModule();
2514 auto &C = CGM.getContext();
2515
2516 // Get list of devices we care about
2517 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2518
2519 // We should be creating an offloading descriptor only if there are devices
2520 // specified.
2521 assert(!Devices.empty() && "No OpenMP offloading devices??");
2522
2523 // Create the external variables that will point to the begin and end of the
2524 // host entries section. These will be defined by the linker.
2525 auto *OffloadEntryTy =
2526 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2527 llvm::GlobalVariable *HostEntriesBegin = 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_begin");
2531 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2532 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002533 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002534 ".omp_offloading.entries_end");
2535
2536 // Create all device images
2537 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2538 auto *DeviceImageTy = cast<llvm::StructType>(
2539 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2540
2541 for (unsigned i = 0; i < Devices.size(); ++i) {
2542 StringRef T = Devices[i].getTriple();
2543 auto *ImgBegin = new llvm::GlobalVariable(
2544 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002545 /*Initializer=*/nullptr,
2546 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002547 auto *ImgEnd = new llvm::GlobalVariable(
2548 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002549 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002550
2551 llvm::Constant *Dev =
2552 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2553 HostEntriesBegin, HostEntriesEnd, nullptr);
2554 DeviceImagesEntires.push_back(Dev);
2555 }
2556
2557 // Create device images global array.
2558 llvm::ArrayType *DeviceImagesInitTy =
2559 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2560 llvm::Constant *DeviceImagesInit =
2561 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2562
2563 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2564 M, DeviceImagesInitTy, /*isConstant=*/true,
2565 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2566 ".omp_offloading.device_images");
2567 DeviceImages->setUnnamedAddr(true);
2568
2569 // This is a Zero array to be used in the creation of the constant expressions
2570 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2571 llvm::Constant::getNullValue(CGM.Int32Ty)};
2572
2573 // Create the target region descriptor.
2574 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2575 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2576 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2577 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2578 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2579 Index),
2580 HostEntriesBegin, HostEntriesEnd, nullptr);
2581
2582 auto *Desc = new llvm::GlobalVariable(
2583 M, BinaryDescriptorTy, /*isConstant=*/true,
2584 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2585 ".omp_offloading.descriptor");
2586
2587 // Emit code to register or unregister the descriptor at execution
2588 // startup or closing, respectively.
2589
2590 // Create a variable to drive the registration and unregistration of the
2591 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2592 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2593 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2594 IdentInfo, C.CharTy);
2595
2596 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2597 CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2598 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2599 Desc);
2600 });
2601 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2602 CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2603 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2604 Desc);
2605 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2606 });
2607 return RegFn;
2608}
2609
Samuel Antao2de62b02016-02-13 23:35:10 +00002610void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2611 llvm::Constant *Addr, uint64_t Size) {
2612 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002613 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2614 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2615 llvm::LLVMContext &C = CGM.getModule().getContext();
2616 llvm::Module &M = CGM.getModule();
2617
2618 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002619 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002620
2621 // Create constant string with the name.
2622 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2623
2624 llvm::GlobalVariable *Str =
2625 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2626 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2627 ".omp_offloading.entry_name");
2628 Str->setUnnamedAddr(true);
2629 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2630
2631 // Create the entry struct.
2632 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2633 TgtOffloadEntryType, AddrPtr, StrPtr,
2634 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2635 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2636 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2637 EntryInit, ".omp_offloading.entry");
2638
2639 // The entry has to be created in the section the linker expects it to be.
2640 Entry->setSection(".omp_offloading.entries");
2641 // We can't have any padding between symbols, so we need to have 1-byte
2642 // alignment.
2643 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002644}
2645
2646void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2647 // Emit the offloading entries and metadata so that the device codegen side
2648 // can
2649 // easily figure out what to emit. The produced metadata looks like this:
2650 //
2651 // !omp_offload.info = !{!1, ...}
2652 //
2653 // Right now we only generate metadata for function that contain target
2654 // regions.
2655
2656 // If we do not have entries, we dont need to do anything.
2657 if (OffloadEntriesInfoManager.empty())
2658 return;
2659
2660 llvm::Module &M = CGM.getModule();
2661 llvm::LLVMContext &C = M.getContext();
2662 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2663 OrderedEntries(OffloadEntriesInfoManager.size());
2664
2665 // Create the offloading info metadata node.
2666 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2667
2668 // Auxiliar methods to create metadata values and strings.
2669 auto getMDInt = [&](unsigned v) {
2670 return llvm::ConstantAsMetadata::get(
2671 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2672 };
2673
2674 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2675
2676 // Create function that emits metadata for each target region entry;
2677 auto &&TargetRegionMetadataEmitter = [&](
2678 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002679 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2680 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2681 // Generate metadata for target regions. Each entry of this metadata
2682 // contains:
2683 // - Entry 0 -> Kind of this type of metadata (0).
2684 // - Entry 1 -> Device ID of the file where the entry was identified.
2685 // - Entry 2 -> File ID of the file where the entry was identified.
2686 // - Entry 3 -> Mangled name of the function where the entry was identified.
2687 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002688 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002689 // The first element of the metadata node is the kind.
2690 Ops.push_back(getMDInt(E.getKind()));
2691 Ops.push_back(getMDInt(DeviceID));
2692 Ops.push_back(getMDInt(FileID));
2693 Ops.push_back(getMDString(ParentName));
2694 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002695 Ops.push_back(getMDInt(E.getOrder()));
2696
2697 // Save this entry in the right position of the ordered entries array.
2698 OrderedEntries[E.getOrder()] = &E;
2699
2700 // Add metadata to the named metadata node.
2701 MD->addOperand(llvm::MDNode::get(C, Ops));
2702 };
2703
2704 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2705 TargetRegionMetadataEmitter);
2706
2707 for (auto *E : OrderedEntries) {
2708 assert(E && "All ordered entries must exist!");
2709 if (auto *CE =
2710 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2711 E)) {
2712 assert(CE->getID() && CE->getAddress() &&
2713 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002714 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002715 } else
2716 llvm_unreachable("Unsupported entry kind.");
2717 }
2718}
2719
2720/// \brief Loads all the offload entries information from the host IR
2721/// metadata.
2722void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2723 // If we are in target mode, load the metadata from the host IR. This code has
2724 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2725
2726 if (!CGM.getLangOpts().OpenMPIsDevice)
2727 return;
2728
2729 if (CGM.getLangOpts().OMPHostIRFile.empty())
2730 return;
2731
2732 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2733 if (Buf.getError())
2734 return;
2735
2736 llvm::LLVMContext C;
2737 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2738
2739 if (ME.getError())
2740 return;
2741
2742 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2743 if (!MD)
2744 return;
2745
2746 for (auto I : MD->operands()) {
2747 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2748
2749 auto getMDInt = [&](unsigned Idx) {
2750 llvm::ConstantAsMetadata *V =
2751 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2752 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2753 };
2754
2755 auto getMDString = [&](unsigned Idx) {
2756 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2757 return V->getString();
2758 };
2759
2760 switch (getMDInt(0)) {
2761 default:
2762 llvm_unreachable("Unexpected metadata!");
2763 break;
2764 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2765 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2766 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2767 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2768 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002769 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002770 break;
2771 }
2772 }
2773}
2774
Alexey Bataev62b63b12015-03-10 07:28:44 +00002775void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2776 if (!KmpRoutineEntryPtrTy) {
2777 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2778 auto &C = CGM.getContext();
2779 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2780 FunctionProtoType::ExtProtoInfo EPI;
2781 KmpRoutineEntryPtrQTy = C.getPointerType(
2782 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2783 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2784 }
2785}
2786
Alexey Bataevc71a4092015-09-11 10:29:41 +00002787static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2788 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002789 auto *Field = FieldDecl::Create(
2790 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2791 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2792 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2793 Field->setAccess(AS_public);
2794 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002795 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002796}
2797
Samuel Antaoee8fb302016-01-06 13:42:12 +00002798QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2799
2800 // Make sure the type of the entry is already created. This is the type we
2801 // have to create:
2802 // struct __tgt_offload_entry{
2803 // void *addr; // Pointer to the offload entry info.
2804 // // (function or global)
2805 // char *name; // Name of the function or global.
2806 // size_t size; // Size of the entry info (0 if it a function).
2807 // };
2808 if (TgtOffloadEntryQTy.isNull()) {
2809 ASTContext &C = CGM.getContext();
2810 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2811 RD->startDefinition();
2812 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2813 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2814 addFieldToRecordDecl(C, RD, C.getSizeType());
2815 RD->completeDefinition();
2816 TgtOffloadEntryQTy = C.getRecordType(RD);
2817 }
2818 return TgtOffloadEntryQTy;
2819}
2820
2821QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2822 // These are the types we need to build:
2823 // struct __tgt_device_image{
2824 // void *ImageStart; // Pointer to the target code start.
2825 // void *ImageEnd; // Pointer to the target code end.
2826 // // We also add the host entries to the device image, as it may be useful
2827 // // for the target runtime to have access to that information.
2828 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2829 // // the entries.
2830 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2831 // // entries (non inclusive).
2832 // };
2833 if (TgtDeviceImageQTy.isNull()) {
2834 ASTContext &C = CGM.getContext();
2835 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2836 RD->startDefinition();
2837 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2838 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2839 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2840 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2841 RD->completeDefinition();
2842 TgtDeviceImageQTy = C.getRecordType(RD);
2843 }
2844 return TgtDeviceImageQTy;
2845}
2846
2847QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2848 // struct __tgt_bin_desc{
2849 // int32_t NumDevices; // Number of devices supported.
2850 // __tgt_device_image *DeviceImages; // Arrays of device images
2851 // // (one per device).
2852 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2853 // // entries.
2854 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2855 // // entries (non inclusive).
2856 // };
2857 if (TgtBinaryDescriptorQTy.isNull()) {
2858 ASTContext &C = CGM.getContext();
2859 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2860 RD->startDefinition();
2861 addFieldToRecordDecl(
2862 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2863 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2864 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2865 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2866 RD->completeDefinition();
2867 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2868 }
2869 return TgtBinaryDescriptorQTy;
2870}
2871
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002872namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002873struct PrivateHelpersTy {
2874 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2875 const VarDecl *PrivateElemInit)
2876 : Original(Original), PrivateCopy(PrivateCopy),
2877 PrivateElemInit(PrivateElemInit) {}
2878 const VarDecl *Original;
2879 const VarDecl *PrivateCopy;
2880 const VarDecl *PrivateElemInit;
2881};
2882typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002883} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002884
Alexey Bataev9e034042015-05-05 04:05:12 +00002885static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002886createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002887 if (!Privates.empty()) {
2888 auto &C = CGM.getContext();
2889 // Build struct .kmp_privates_t. {
2890 // /* private vars */
2891 // };
2892 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2893 RD->startDefinition();
2894 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002895 auto *VD = Pair.second.Original;
2896 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002897 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002898 auto *FD = addFieldToRecordDecl(C, RD, Type);
2899 if (VD->hasAttrs()) {
2900 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2901 E(VD->getAttrs().end());
2902 I != E; ++I)
2903 FD->addAttr(*I);
2904 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002905 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002906 RD->completeDefinition();
2907 return RD;
2908 }
2909 return nullptr;
2910}
2911
Alexey Bataev9e034042015-05-05 04:05:12 +00002912static RecordDecl *
2913createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002914 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002915 auto &C = CGM.getContext();
2916 // Build struct kmp_task_t {
2917 // void * shareds;
2918 // kmp_routine_entry_t routine;
2919 // kmp_int32 part_id;
2920 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002921 // };
2922 auto *RD = C.buildImplicitRecord("kmp_task_t");
2923 RD->startDefinition();
2924 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2925 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2926 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2927 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002928 RD->completeDefinition();
2929 return RD;
2930}
2931
2932static RecordDecl *
2933createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002934 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002935 auto &C = CGM.getContext();
2936 // Build struct kmp_task_t_with_privates {
2937 // kmp_task_t task_data;
2938 // .kmp_privates_t. privates;
2939 // };
2940 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2941 RD->startDefinition();
2942 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002943 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2944 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2945 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002946 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002947 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002948}
2949
2950/// \brief Emit a proxy function which accepts kmp_task_t as the second
2951/// argument.
2952/// \code
2953/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002954/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2955/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002956/// return 0;
2957/// }
2958/// \endcode
2959static llvm::Value *
2960emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002961 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2962 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002963 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2964 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002965 auto &C = CGM.getContext();
2966 FunctionArgList Args;
2967 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2968 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002969 /*Id=*/nullptr,
2970 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002971 Args.push_back(&GtidArg);
2972 Args.push_back(&TaskTypeArg);
2973 FunctionType::ExtInfo Info;
2974 auto &TaskEntryFnInfo =
2975 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2976 /*isVariadic=*/false);
2977 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2978 auto *TaskEntry =
2979 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2980 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002981 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002982 CodeGenFunction CGF(CGM);
2983 CGF.disableDebugInfo();
2984 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2985
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002986 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2987 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002988 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002989 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002990 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2991 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2992 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002993 auto *KmpTaskTWithPrivatesQTyRD =
2994 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002995 LValue Base =
2996 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002997 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2998 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2999 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3000 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
3001
3002 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3003 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003004 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003005 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003006 CGF.ConvertTypeForMem(SharedsPtrTy));
3007
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003008 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3009 llvm::Value *PrivatesParam;
3010 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3011 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3012 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003013 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003014 } else {
3015 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3016 }
3017
3018 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
3019 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003020 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3021 CGF.EmitStoreThroughLValue(
3022 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003023 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003024 CGF.FinishFunction();
3025 return TaskEntry;
3026}
3027
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003028static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3029 SourceLocation Loc,
3030 QualType KmpInt32Ty,
3031 QualType KmpTaskTWithPrivatesPtrQTy,
3032 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003033 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003034 FunctionArgList Args;
3035 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3036 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003037 /*Id=*/nullptr,
3038 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003039 Args.push_back(&GtidArg);
3040 Args.push_back(&TaskTypeArg);
3041 FunctionType::ExtInfo Info;
3042 auto &DestructorFnInfo =
3043 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
3044 /*isVariadic=*/false);
3045 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3046 auto *DestructorFn =
3047 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3048 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003049 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3050 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003051 CodeGenFunction CGF(CGM);
3052 CGF.disableDebugInfo();
3053 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3054 Args);
3055
Alexey Bataev31300ed2016-02-04 11:27:03 +00003056 LValue Base = CGF.EmitLoadOfPointerLValue(
3057 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3058 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003059 auto *KmpTaskTWithPrivatesQTyRD =
3060 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3061 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003062 Base = CGF.EmitLValueForField(Base, *FI);
3063 for (auto *Field :
3064 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3065 if (auto DtorKind = Field->getType().isDestructedType()) {
3066 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3067 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3068 }
3069 }
3070 CGF.FinishFunction();
3071 return DestructorFn;
3072}
3073
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003074/// \brief Emit a privates mapping function for correct handling of private and
3075/// firstprivate variables.
3076/// \code
3077/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3078/// **noalias priv1,..., <tyn> **noalias privn) {
3079/// *priv1 = &.privates.priv1;
3080/// ...;
3081/// *privn = &.privates.privn;
3082/// }
3083/// \endcode
3084static llvm::Value *
3085emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003086 ArrayRef<const Expr *> PrivateVars,
3087 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003088 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003089 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003090 auto &C = CGM.getContext();
3091 FunctionArgList Args;
3092 ImplicitParamDecl TaskPrivatesArg(
3093 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3094 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3095 Args.push_back(&TaskPrivatesArg);
3096 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3097 unsigned Counter = 1;
3098 for (auto *E: PrivateVars) {
3099 Args.push_back(ImplicitParamDecl::Create(
3100 C, /*DC=*/nullptr, Loc,
3101 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3102 .withConst()
3103 .withRestrict()));
3104 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3105 PrivateVarsPos[VD] = Counter;
3106 ++Counter;
3107 }
3108 for (auto *E : FirstprivateVars) {
3109 Args.push_back(ImplicitParamDecl::Create(
3110 C, /*DC=*/nullptr, Loc,
3111 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3112 .withConst()
3113 .withRestrict()));
3114 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3115 PrivateVarsPos[VD] = Counter;
3116 ++Counter;
3117 }
3118 FunctionType::ExtInfo Info;
3119 auto &TaskPrivatesMapFnInfo =
3120 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
3121 /*isVariadic=*/false);
3122 auto *TaskPrivatesMapTy =
3123 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3124 auto *TaskPrivatesMap = llvm::Function::Create(
3125 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3126 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003127 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3128 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003129 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003130 CodeGenFunction CGF(CGM);
3131 CGF.disableDebugInfo();
3132 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3133 TaskPrivatesMapFnInfo, Args);
3134
3135 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003136 LValue Base = CGF.EmitLoadOfPointerLValue(
3137 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3138 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003139 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3140 Counter = 0;
3141 for (auto *Field : PrivatesQTyRD->fields()) {
3142 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3143 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003144 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003145 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3146 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003147 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003148 ++Counter;
3149 }
3150 CGF.FinishFunction();
3151 return TaskPrivatesMap;
3152}
3153
Alexey Bataev9e034042015-05-05 04:05:12 +00003154static int array_pod_sort_comparator(const PrivateDataTy *P1,
3155 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003156 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3157}
3158
3159void CGOpenMPRuntime::emitTaskCall(
3160 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3161 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00003162 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003163 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3164 ArrayRef<const Expr *> PrivateCopies,
3165 ArrayRef<const Expr *> FirstprivateVars,
3166 ArrayRef<const Expr *> FirstprivateCopies,
3167 ArrayRef<const Expr *> FirstprivateInits,
3168 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003169 if (!CGF.HaveInsertPoint())
3170 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003171 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00003172 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003173 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003174 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003175 for (auto *E : PrivateVars) {
3176 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3177 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003178 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003179 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3180 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003181 ++I;
3182 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003183 I = FirstprivateCopies.begin();
3184 auto IElemInitRef = FirstprivateInits.begin();
3185 for (auto *E : FirstprivateVars) {
3186 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3187 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003188 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003189 PrivateHelpersTy(
3190 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3191 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003192 ++I;
3193 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003194 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003195 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3196 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003197 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3198 // Build type kmp_routine_entry_t (if not built yet).
3199 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003200 // Build type kmp_task_t (if not built yet).
3201 if (KmpTaskTQTy.isNull()) {
3202 KmpTaskTQTy = C.getRecordType(
3203 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
3204 }
3205 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003206 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003207 auto *KmpTaskTWithPrivatesQTyRD =
3208 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3209 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3210 QualType KmpTaskTWithPrivatesPtrQTy =
3211 C.getPointerType(KmpTaskTWithPrivatesQTy);
3212 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3213 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003214 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003215 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3216
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003217 // Emit initial values for private copies (if any).
3218 llvm::Value *TaskPrivatesMap = nullptr;
3219 auto *TaskPrivatesMapTy =
3220 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3221 3)
3222 ->getType();
3223 if (!Privates.empty()) {
3224 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3225 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3226 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3227 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3228 TaskPrivatesMap, TaskPrivatesMapTy);
3229 } else {
3230 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3231 cast<llvm::PointerType>(TaskPrivatesMapTy));
3232 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003233 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3234 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003235 auto *TaskEntry = emitProxyTaskFunction(
3236 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003237 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003238
3239 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3240 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3241 // kmp_routine_entry_t *task_entry);
3242 // Task flags. Format is taken from
3243 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3244 // description of kmp_tasking_flags struct.
3245 const unsigned TiedFlag = 0x1;
3246 const unsigned FinalFlag = 0x2;
3247 unsigned Flags = Tied ? TiedFlag : 0;
3248 auto *TaskFlags =
3249 Final.getPointer()
3250 ? CGF.Builder.CreateSelect(Final.getPointer(),
3251 CGF.Builder.getInt32(FinalFlag),
3252 CGF.Builder.getInt32(/*C=*/0))
3253 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3254 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003255 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003256 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3257 getThreadID(CGF, Loc), TaskFlags,
3258 KmpTaskTWithPrivatesTySize, SharedsSize,
3259 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3260 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003261 auto *NewTask = CGF.EmitRuntimeCall(
3262 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003263 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3264 NewTask, KmpTaskTWithPrivatesPtrTy);
3265 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3266 KmpTaskTWithPrivatesQTy);
3267 LValue TDBase =
3268 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003269 // Fill the data in the resulting kmp_task_t record.
3270 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003271 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003272 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003273 KmpTaskSharedsPtr =
3274 Address(CGF.EmitLoadOfScalar(
3275 CGF.EmitLValueForField(
3276 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3277 KmpTaskTShareds)),
3278 Loc),
3279 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003280 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003281 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003282 // Emit initial values for private copies (if any).
3283 bool NeedsCleanup = false;
3284 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003285 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3286 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003287 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003288 LValue SharedsBase;
3289 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003290 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003291 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3292 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3293 SharedsTy);
3294 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003295 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3296 cast<CapturedStmt>(*D.getAssociatedStmt()));
3297 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003298 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003299 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003300 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003301 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003302 if (auto *Elem = Pair.second.PrivateElemInit) {
3303 auto *OriginalVD = Pair.second.Original;
3304 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3305 auto SharedRefLValue =
3306 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003307 SharedRefLValue = CGF.MakeAddrLValue(
3308 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3309 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003310 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003311 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003312 // Initialize firstprivate array.
3313 if (!isa<CXXConstructExpr>(Init) ||
3314 CGF.isTrivialInitializer(Init)) {
3315 // Perform simple memcpy.
3316 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003317 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003318 } else {
3319 // Initialize firstprivate array using element-by-element
3320 // intialization.
3321 CGF.EmitOMPAggregateAssign(
3322 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003323 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003324 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003325 // Clean up any temporaries needed by the initialization.
3326 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003327 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003328 return SrcElement;
3329 });
3330 (void)InitScope.Privatize();
3331 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003332 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3333 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003334 CGF.EmitAnyExprToMem(Init, DestElement,
3335 Init->getType().getQualifiers(),
3336 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003337 });
3338 }
3339 } else {
3340 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003341 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003342 return SharedRefLValue.getAddress();
3343 });
3344 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003345 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003346 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3347 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003348 }
3349 } else {
3350 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3351 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003352 }
3353 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003354 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003355 }
3356 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003357 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003358 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003359 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3360 KmpTaskTWithPrivatesPtrQTy,
3361 KmpTaskTWithPrivatesQTy)
3362 : llvm::ConstantPointerNull::get(
3363 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3364 LValue Destructor = CGF.EmitLValueForField(
3365 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3366 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3367 DestructorFn, KmpRoutineEntryPtrTy),
3368 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003369
3370 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003371 Address DependenciesArray = Address::invalid();
3372 unsigned NumDependencies = Dependences.size();
3373 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003374 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003375 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003376 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3377 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003378 QualType FlagsTy =
3379 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003380 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3381 if (KmpDependInfoTy.isNull()) {
3382 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3383 KmpDependInfoRD->startDefinition();
3384 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3385 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3386 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3387 KmpDependInfoRD->completeDefinition();
3388 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3389 } else {
3390 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3391 }
John McCall7f416cc2015-09-08 08:05:57 +00003392 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003393 // Define type kmp_depend_info[<Dependences.size()>];
3394 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003395 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003396 ArrayType::Normal, /*IndexTypeQuals=*/0);
3397 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00003398 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
3399 for (unsigned i = 0; i < NumDependencies; ++i) {
3400 const Expr *E = Dependences[i].second;
3401 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003402 llvm::Value *Size;
3403 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003404 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3405 LValue UpAddrLVal =
3406 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3407 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003408 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003409 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003410 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003411 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3412 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003413 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003414 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003415 auto Base = CGF.MakeAddrLValue(
3416 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003417 KmpDependInfoTy);
3418 // deps[i].base_addr = &<Dependences[i].second>;
3419 auto BaseAddrLVal = CGF.EmitLValueForField(
3420 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003421 CGF.EmitStoreOfScalar(
3422 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3423 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003424 // deps[i].len = sizeof(<Dependences[i].second>);
3425 auto LenLVal = CGF.EmitLValueForField(
3426 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3427 CGF.EmitStoreOfScalar(Size, LenLVal);
3428 // deps[i].flags = <Dependences[i].first>;
3429 RTLDependenceKindTy DepKind;
3430 switch (Dependences[i].first) {
3431 case OMPC_DEPEND_in:
3432 DepKind = DepIn;
3433 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003434 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003435 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003436 case OMPC_DEPEND_inout:
3437 DepKind = DepInOut;
3438 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003439 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003440 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003441 case OMPC_DEPEND_unknown:
3442 llvm_unreachable("Unknown task dependence type");
3443 }
3444 auto FlagsLVal = CGF.EmitLValueForField(
3445 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3446 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3447 FlagsLVal);
3448 }
John McCall7f416cc2015-09-08 08:05:57 +00003449 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3450 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003451 CGF.VoidPtrTy);
3452 }
3453
Alexey Bataev62b63b12015-03-10 07:28:44 +00003454 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3455 // libcall.
3456 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3457 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003458 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3459 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3460 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3461 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003462 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003463 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003464 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3465 llvm::Value *DepTaskArgs[7];
3466 if (NumDependencies) {
3467 DepTaskArgs[0] = UpLoc;
3468 DepTaskArgs[1] = ThreadID;
3469 DepTaskArgs[2] = NewTask;
3470 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3471 DepTaskArgs[4] = DependenciesArray.getPointer();
3472 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3473 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3474 }
3475 auto &&ThenCodeGen = [this, NumDependencies,
3476 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3477 // TODO: add check for untied tasks.
3478 if (NumDependencies) {
3479 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3480 DepTaskArgs);
3481 } else {
3482 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3483 TaskArgs);
3484 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003485 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003486 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3487 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00003488
3489 llvm::Value *DepWaitTaskArgs[6];
3490 if (NumDependencies) {
3491 DepWaitTaskArgs[0] = UpLoc;
3492 DepWaitTaskArgs[1] = ThreadID;
3493 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3494 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3495 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3496 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3497 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003498 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00003499 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003500 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3501 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3502 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3503 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3504 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003505 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003506 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3507 DepWaitTaskArgs);
3508 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3509 // kmp_task_t *new_task);
3510 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3511 TaskArgs);
3512 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3513 // kmp_task_t *new_task);
3514 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3515 NormalAndEHCleanup,
3516 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3517 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00003518
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003519 // Call proxy_task_entry(gtid, new_task);
3520 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3521 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3522 };
John McCall7f416cc2015-09-08 08:05:57 +00003523
Alexey Bataev1d677132015-04-22 13:57:31 +00003524 if (IfCond) {
3525 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3526 } else {
3527 CodeGenFunction::RunCleanupsScope Scope(CGF);
3528 ThenCodeGen(CGF);
3529 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003530}
3531
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003532/// \brief Emit reduction operation for each element of array (required for
3533/// array sections) LHS op = RHS.
3534/// \param Type Type of array.
3535/// \param LHSVar Variable on the left side of the reduction operation
3536/// (references element of array in original variable).
3537/// \param RHSVar Variable on the right side of the reduction operation
3538/// (references element of array in original variable).
3539/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3540/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003541static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003542 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3543 const VarDecl *RHSVar,
3544 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3545 const Expr *, const Expr *)> &RedOpGen,
3546 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3547 const Expr *UpExpr = nullptr) {
3548 // Perform element-by-element initialization.
3549 QualType ElementTy;
3550 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3551 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3552
3553 // Drill down to the base element type on both arrays.
3554 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3555 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3556
3557 auto RHSBegin = RHSAddr.getPointer();
3558 auto LHSBegin = LHSAddr.getPointer();
3559 // Cast from pointer to array type to pointer to single element.
3560 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3561 // The basic structure here is a while-do loop.
3562 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3563 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3564 auto IsEmpty =
3565 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3566 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3567
3568 // Enter the loop body, making that address the current address.
3569 auto EntryBB = CGF.Builder.GetInsertBlock();
3570 CGF.EmitBlock(BodyBB);
3571
3572 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3573
3574 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3575 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3576 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3577 Address RHSElementCurrent =
3578 Address(RHSElementPHI,
3579 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3580
3581 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3582 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3583 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3584 Address LHSElementCurrent =
3585 Address(LHSElementPHI,
3586 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3587
3588 // Emit copy.
3589 CodeGenFunction::OMPPrivateScope Scope(CGF);
3590 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3591 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3592 Scope.Privatize();
3593 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3594 Scope.ForceCleanup();
3595
3596 // Shift the address forward by one element.
3597 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3598 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3599 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3600 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3601 // Check whether we've reached the end.
3602 auto Done =
3603 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3604 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3605 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3606 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3607
3608 // Done.
3609 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3610}
3611
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003612static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3613 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003614 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003615 ArrayRef<const Expr *> LHSExprs,
3616 ArrayRef<const Expr *> RHSExprs,
3617 ArrayRef<const Expr *> ReductionOps) {
3618 auto &C = CGM.getContext();
3619
3620 // void reduction_func(void *LHSArg, void *RHSArg);
3621 FunctionArgList Args;
3622 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3623 C.VoidPtrTy);
3624 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3625 C.VoidPtrTy);
3626 Args.push_back(&LHSArg);
3627 Args.push_back(&RHSArg);
3628 FunctionType::ExtInfo EI;
3629 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3630 C.VoidTy, Args, EI, /*isVariadic=*/false);
3631 auto *Fn = llvm::Function::Create(
3632 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3633 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003634 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003635 CodeGenFunction CGF(CGM);
3636 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3637
3638 // Dst = (void*[n])(LHSArg);
3639 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003640 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3641 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3642 ArgsType), CGF.getPointerAlign());
3643 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3644 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3645 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003646
3647 // ...
3648 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3649 // ...
3650 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003651 auto IPriv = Privates.begin();
3652 unsigned Idx = 0;
3653 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003654 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3655 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003656 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003657 });
3658 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3659 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003660 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003661 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003662 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003663 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003664 // Get array size and emit VLA type.
3665 ++Idx;
3666 Address Elem =
3667 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3668 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003669 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3670 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003671 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003672 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003673 CGF.EmitVariablyModifiedType(PrivTy);
3674 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003675 }
3676 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003677 IPriv = Privates.begin();
3678 auto ILHS = LHSExprs.begin();
3679 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003680 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003681 if ((*IPriv)->getType()->isArrayType()) {
3682 // Emit reduction for array section.
3683 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3684 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3685 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3686 [=](CodeGenFunction &CGF, const Expr *,
3687 const Expr *,
3688 const Expr *) { CGF.EmitIgnoredExpr(E); });
3689 } else
3690 // Emit reduction for array subscript or single variable.
3691 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003692 ++IPriv;
3693 ++ILHS;
3694 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003695 }
3696 Scope.ForceCleanup();
3697 CGF.FinishFunction();
3698 return Fn;
3699}
3700
3701void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003702 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003703 ArrayRef<const Expr *> LHSExprs,
3704 ArrayRef<const Expr *> RHSExprs,
3705 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003706 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003707 if (!CGF.HaveInsertPoint())
3708 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003709 // Next code should be emitted for reduction:
3710 //
3711 // static kmp_critical_name lock = { 0 };
3712 //
3713 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3714 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3715 // ...
3716 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3717 // *(Type<n>-1*)rhs[<n>-1]);
3718 // }
3719 //
3720 // ...
3721 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3722 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3723 // RedList, reduce_func, &<lock>)) {
3724 // case 1:
3725 // ...
3726 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3727 // ...
3728 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3729 // break;
3730 // case 2:
3731 // ...
3732 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3733 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003734 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003735 // break;
3736 // default:;
3737 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003738 //
3739 // if SimpleReduction is true, only the next code is generated:
3740 // ...
3741 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3742 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003743
3744 auto &C = CGM.getContext();
3745
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003746 if (SimpleReduction) {
3747 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003748 auto IPriv = Privates.begin();
3749 auto ILHS = LHSExprs.begin();
3750 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003751 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003752 if ((*IPriv)->getType()->isArrayType()) {
3753 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3754 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3755 EmitOMPAggregateReduction(
3756 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3757 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3758 const Expr *) { CGF.EmitIgnoredExpr(E); });
3759 } else
3760 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003761 ++IPriv;
3762 ++ILHS;
3763 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003764 }
3765 return;
3766 }
3767
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003768 // 1. Build a list of reduction variables.
3769 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003770 auto Size = RHSExprs.size();
3771 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003772 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003773 // Reserve place for array size.
3774 ++Size;
3775 }
3776 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003777 QualType ReductionArrayTy =
3778 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3779 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003780 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003781 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003782 auto IPriv = Privates.begin();
3783 unsigned Idx = 0;
3784 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003785 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003786 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003787 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003788 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003789 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3790 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003791 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003792 // Store array size.
3793 ++Idx;
3794 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3795 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003796 llvm::Value *Size = CGF.Builder.CreateIntCast(
3797 CGF.getVLASize(
3798 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3799 .first,
3800 CGF.SizeTy, /*isSigned=*/false);
3801 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3802 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003803 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003804 }
3805
3806 // 2. Emit reduce_func().
3807 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003808 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3809 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003810
3811 // 3. Create static kmp_critical_name lock = { 0 };
3812 auto *Lock = getCriticalRegionLock(".reduction");
3813
3814 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3815 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003816 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003817 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003818 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003819 auto *RL =
3820 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3821 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003822 llvm::Value *Args[] = {
3823 IdentTLoc, // ident_t *<loc>
3824 ThreadId, // i32 <gtid>
3825 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3826 ReductionArrayTySize, // size_type sizeof(RedList)
3827 RL, // void *RedList
3828 ReductionFn, // void (*) (void *, void *) <reduce_func>
3829 Lock // kmp_critical_name *&<lock>
3830 };
3831 auto Res = CGF.EmitRuntimeCall(
3832 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3833 : OMPRTL__kmpc_reduce),
3834 Args);
3835
3836 // 5. Build switch(res)
3837 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3838 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3839
3840 // 6. Build case 1:
3841 // ...
3842 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3843 // ...
3844 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3845 // break;
3846 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3847 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3848 CGF.EmitBlock(Case1BB);
3849
3850 {
3851 CodeGenFunction::RunCleanupsScope Scope(CGF);
3852 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3853 llvm::Value *EndArgs[] = {
3854 IdentTLoc, // ident_t *<loc>
3855 ThreadId, // i32 <gtid>
3856 Lock // kmp_critical_name *&<lock>
3857 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003858 CGF.EHStack
3859 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3860 NormalAndEHCleanup,
3861 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3862 : OMPRTL__kmpc_end_reduce),
3863 llvm::makeArrayRef(EndArgs));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003864 auto IPriv = Privates.begin();
3865 auto ILHS = LHSExprs.begin();
3866 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003867 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003868 if ((*IPriv)->getType()->isArrayType()) {
3869 // Emit reduction for array section.
3870 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3871 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3872 EmitOMPAggregateReduction(
3873 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3874 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3875 const Expr *) { CGF.EmitIgnoredExpr(E); });
3876 } else
3877 // Emit reduction for array subscript or single variable.
3878 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003879 ++IPriv;
3880 ++ILHS;
3881 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003882 }
3883 }
3884
3885 CGF.EmitBranch(DefaultBB);
3886
3887 // 7. Build case 2:
3888 // ...
3889 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3890 // ...
3891 // break;
3892 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3893 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3894 CGF.EmitBlock(Case2BB);
3895
3896 {
3897 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00003898 if (!WithNowait) {
3899 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3900 llvm::Value *EndArgs[] = {
3901 IdentTLoc, // ident_t *<loc>
3902 ThreadId, // i32 <gtid>
3903 Lock // kmp_critical_name *&<lock>
3904 };
3905 CGF.EHStack
3906 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3907 NormalAndEHCleanup,
3908 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3909 llvm::makeArrayRef(EndArgs));
3910 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003911 auto ILHS = LHSExprs.begin();
3912 auto IRHS = RHSExprs.begin();
3913 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003914 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003915 const Expr *XExpr = nullptr;
3916 const Expr *EExpr = nullptr;
3917 const Expr *UpExpr = nullptr;
3918 BinaryOperatorKind BO = BO_Comma;
3919 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3920 if (BO->getOpcode() == BO_Assign) {
3921 XExpr = BO->getLHS();
3922 UpExpr = BO->getRHS();
3923 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003924 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003925 // Try to emit update expression as a simple atomic.
3926 auto *RHSExpr = UpExpr;
3927 if (RHSExpr) {
3928 // Analyze RHS part of the whole expression.
3929 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3930 RHSExpr->IgnoreParenImpCasts())) {
3931 // If this is a conditional operator, analyze its condition for
3932 // min/max reduction operator.
3933 RHSExpr = ACO->getCond();
3934 }
3935 if (auto *BORHS =
3936 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3937 EExpr = BORHS->getRHS();
3938 BO = BORHS->getOpcode();
3939 }
Alexey Bataev69a47792015-05-07 03:54:03 +00003940 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003941 if (XExpr) {
3942 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3943 auto &&AtomicRedGen = [this, BO, VD, IPriv,
3944 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3945 const Expr *EExpr, const Expr *UpExpr) {
3946 LValue X = CGF.EmitLValue(XExpr);
3947 RValue E;
3948 if (EExpr)
3949 E = CGF.EmitAnyExpr(EExpr);
3950 CGF.EmitOMPAtomicSimpleUpdateExpr(
3951 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
Alexey Bataev8524d152016-01-21 12:35:58 +00003952 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003953 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev8524d152016-01-21 12:35:58 +00003954 PrivateScope.addPrivate(
3955 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3956 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3957 CGF.emitOMPSimpleStore(
3958 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3959 VD->getType().getNonReferenceType(), Loc);
3960 return LHSTemp;
3961 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003962 (void)PrivateScope.Privatize();
3963 return CGF.EmitAnyExpr(UpExpr);
3964 });
3965 };
3966 if ((*IPriv)->getType()->isArrayType()) {
3967 // Emit atomic reduction for array section.
3968 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3969 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3970 AtomicRedGen, XExpr, EExpr, UpExpr);
3971 } else
3972 // Emit atomic reduction for array subscript or single variable.
3973 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3974 } else {
3975 // Emit as a critical region.
3976 auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3977 const Expr *, const Expr *) {
3978 emitCriticalRegion(
3979 CGF, ".atomic_reduction",
3980 [E](CodeGenFunction &CGF) { CGF.EmitIgnoredExpr(E); }, Loc);
3981 };
3982 if ((*IPriv)->getType()->isArrayType()) {
3983 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3984 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3985 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3986 CritRedGen);
3987 } else
3988 CritRedGen(CGF, nullptr, nullptr, nullptr);
3989 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003990 ++ILHS;
3991 ++IRHS;
3992 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003993 }
3994 }
3995
3996 CGF.EmitBranch(DefaultBB);
3997 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3998}
3999
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004000void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4001 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004002 if (!CGF.HaveInsertPoint())
4003 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004004 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4005 // global_tid);
4006 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4007 // Ignore return result until untied tasks are supported.
4008 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
4009}
4010
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004011void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004012 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004013 const RegionCodeGenTy &CodeGen,
4014 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004015 if (!CGF.HaveInsertPoint())
4016 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004017 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004018 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004019}
4020
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004021namespace {
4022enum RTCancelKind {
4023 CancelNoreq = 0,
4024 CancelParallel = 1,
4025 CancelLoop = 2,
4026 CancelSections = 3,
4027 CancelTaskgroup = 4
4028};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004029} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004030
4031static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4032 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004033 if (CancelRegion == OMPD_parallel)
4034 CancelKind = CancelParallel;
4035 else if (CancelRegion == OMPD_for)
4036 CancelKind = CancelLoop;
4037 else if (CancelRegion == OMPD_sections)
4038 CancelKind = CancelSections;
4039 else {
4040 assert(CancelRegion == OMPD_taskgroup);
4041 CancelKind = CancelTaskgroup;
4042 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004043 return CancelKind;
4044}
4045
4046void CGOpenMPRuntime::emitCancellationPointCall(
4047 CodeGenFunction &CGF, SourceLocation Loc,
4048 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004049 if (!CGF.HaveInsertPoint())
4050 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004051 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4052 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004053 if (auto *OMPRegionInfo =
4054 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004055 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004056 llvm::Value *Args[] = {
4057 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4058 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004059 // Ignore return result until untied tasks are supported.
4060 auto *Result = CGF.EmitRuntimeCall(
4061 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4062 // if (__kmpc_cancellationpoint()) {
4063 // __kmpc_cancel_barrier();
4064 // exit from construct;
4065 // }
4066 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4067 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4068 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4069 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4070 CGF.EmitBlock(ExitBB);
4071 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004072 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004073 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004074 auto CancelDest =
4075 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004076 CGF.EmitBranchThroughCleanup(CancelDest);
4077 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4078 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004079 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004080}
4081
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004082void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004083 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004084 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004085 if (!CGF.HaveInsertPoint())
4086 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004087 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4088 // kmp_int32 cncl_kind);
4089 if (auto *OMPRegionInfo =
4090 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004091 auto &&ThenGen = [this, Loc, CancelRegion,
4092 OMPRegionInfo](CodeGenFunction &CGF) {
4093 llvm::Value *Args[] = {
4094 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4095 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4096 // Ignore return result until untied tasks are supported.
4097 auto *Result =
4098 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
4099 // if (__kmpc_cancel()) {
4100 // __kmpc_cancel_barrier();
4101 // exit from construct;
4102 // }
4103 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4104 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4105 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4106 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4107 CGF.EmitBlock(ExitBB);
4108 // __kmpc_cancel_barrier();
4109 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4110 // exit from construct;
4111 auto CancelDest =
4112 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4113 CGF.EmitBranchThroughCleanup(CancelDest);
4114 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4115 };
4116 if (IfCond)
4117 emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
4118 else
4119 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004120 }
4121}
Samuel Antaobed3c462015-10-02 16:14:20 +00004122
Samuel Antaoee8fb302016-01-06 13:42:12 +00004123/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004124/// consists of the file and device IDs as well as line number associated with
4125/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004126static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4127 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004128 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004129
4130 auto &SM = C.getSourceManager();
4131
4132 // The loc should be always valid and have a file ID (the user cannot use
4133 // #pragma directives in macros)
4134
4135 assert(Loc.isValid() && "Source location is expected to be always valid.");
4136 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4137
4138 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4139 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4140
4141 llvm::sys::fs::UniqueID ID;
4142 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4143 llvm_unreachable("Source file with target region no longer exists!");
4144
4145 DeviceID = ID.getDevice();
4146 FileID = ID.getFile();
4147 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004148}
4149
4150void CGOpenMPRuntime::emitTargetOutlinedFunction(
4151 const OMPExecutableDirective &D, StringRef ParentName,
4152 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4153 bool IsOffloadEntry) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004154 assert(!ParentName.empty() && "Invalid target region parent name!");
4155
Samuel Antaobed3c462015-10-02 16:14:20 +00004156 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4157
Samuel Antaoee8fb302016-01-06 13:42:12 +00004158 // Emit target region as a standalone region.
4159 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
4160 CGF.EmitStmt(CS.getCapturedStmt());
4161 };
4162
Samuel Antao2de62b02016-02-13 23:35:10 +00004163 // Create a unique name for the entry function using the source location
4164 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004165 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004166 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004167 //
4168 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004169 // mangled name of the function that encloses the target region and BB is the
4170 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004171
4172 unsigned DeviceID;
4173 unsigned FileID;
4174 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004175 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004176 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004177 SmallString<64> EntryFnName;
4178 {
4179 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004180 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4181 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004182 }
4183
Samuel Antaobed3c462015-10-02 16:14:20 +00004184 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004185 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004186 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004187
4188 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4189
4190 // If this target outline function is not an offload entry, we don't need to
4191 // register it.
4192 if (!IsOffloadEntry)
4193 return;
4194
4195 // The target region ID is used by the runtime library to identify the current
4196 // target region, so it only has to be unique and not necessarily point to
4197 // anything. It could be the pointer to the outlined function that implements
4198 // the target region, but we aren't using that so that the compiler doesn't
4199 // need to keep that, and could therefore inline the host function if proven
4200 // worthwhile during optimization. In the other hand, if emitting code for the
4201 // device, the ID has to be the function address so that it can retrieved from
4202 // the offloading entry and launched by the runtime library. We also mark the
4203 // outlined function to have external linkage in case we are emitting code for
4204 // the device, because these functions will be entry points to the device.
4205
4206 if (CGM.getLangOpts().OpenMPIsDevice) {
4207 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4208 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4209 } else
4210 OutlinedFnID = new llvm::GlobalVariable(
4211 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4212 llvm::GlobalValue::PrivateLinkage,
4213 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4214
4215 // Register the information for the entry associated with this target region.
4216 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004217 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004218}
4219
Samuel Antaob68e2db2016-03-03 16:20:23 +00004220/// \brief Emit the num_teams clause of an enclosed teams directive at the
4221/// target region scope. If there is no teams directive associated with the
4222/// target directive, or if there is no num_teams clause associated with the
4223/// enclosed teams directive, return nullptr.
4224static llvm::Value *
4225emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4226 CodeGenFunction &CGF,
4227 const OMPExecutableDirective &D) {
4228
4229 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4230 "teams directive expected to be "
4231 "emitted only for the host!");
4232
4233 // FIXME: For the moment we do not support combined directives with target and
4234 // teams, so we do not expect to get any num_teams clause in the provided
4235 // directive. Once we support that, this assertion can be replaced by the
4236 // actual emission of the clause expression.
4237 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4238 "Not expecting clause in directive.");
4239
4240 // If the current target region has a teams region enclosed, we need to get
4241 // the number of teams to pass to the runtime function call. This is done
4242 // by generating the expression in a inlined region. This is required because
4243 // the expression is captured in the enclosing target environment when the
4244 // teams directive is not combined with target.
4245
4246 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4247
4248 // FIXME: Accommodate other combined directives with teams when they become
4249 // available.
4250 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4251 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4252 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4253 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4254 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4255 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4256 /*IsSigned=*/true);
4257 }
4258
4259 // If we have an enclosed teams directive but no num_teams clause we use
4260 // the default value 0.
4261 return CGF.Builder.getInt32(0);
4262 }
4263
4264 // No teams associated with the directive.
4265 return nullptr;
4266}
4267
4268/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4269/// target region scope. If there is no teams directive associated with the
4270/// target directive, or if there is no thread_limit clause associated with the
4271/// enclosed teams directive, return nullptr.
4272static llvm::Value *
4273emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4274 CodeGenFunction &CGF,
4275 const OMPExecutableDirective &D) {
4276
4277 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4278 "teams directive expected to be "
4279 "emitted only for the host!");
4280
4281 // FIXME: For the moment we do not support combined directives with target and
4282 // teams, so we do not expect to get any thread_limit clause in the provided
4283 // directive. Once we support that, this assertion can be replaced by the
4284 // actual emission of the clause expression.
4285 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4286 "Not expecting clause in directive.");
4287
4288 // If the current target region has a teams region enclosed, we need to get
4289 // the thread limit to pass to the runtime function call. This is done
4290 // by generating the expression in a inlined region. This is required because
4291 // the expression is captured in the enclosing target environment when the
4292 // teams directive is not combined with target.
4293
4294 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4295
4296 // FIXME: Accommodate other combined directives with teams when they become
4297 // available.
4298 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4299 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4300 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4301 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4302 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4303 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4304 /*IsSigned=*/true);
4305 }
4306
4307 // If we have an enclosed teams directive but no thread_limit clause we use
4308 // the default value 0.
4309 return CGF.Builder.getInt32(0);
4310 }
4311
4312 // No teams associated with the directive.
4313 return nullptr;
4314}
4315
Samuel Antaobed3c462015-10-02 16:14:20 +00004316void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
4317 const OMPExecutableDirective &D,
4318 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004319 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00004320 const Expr *IfCond, const Expr *Device,
4321 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004322 if (!CGF.HaveInsertPoint())
4323 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00004324 /// \brief Values for bit flags used to specify the mapping type for
4325 /// offloading.
4326 enum OpenMPOffloadMappingFlags {
4327 /// \brief Allocate memory on the device and move data from host to device.
4328 OMP_MAP_TO = 0x01,
4329 /// \brief Allocate memory on the device and move data from device to host.
4330 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004331 /// \brief The element passed to the device is a pointer.
4332 OMP_MAP_PTR = 0x20,
4333 /// \brief Pass the element to the device by value.
4334 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00004335 };
4336
4337 enum OpenMPOffloadingReservedDeviceIDs {
4338 /// \brief Device ID if the device was not defined, runtime should get it
4339 /// from environment variables in the spec.
4340 OMP_DEVICEID_UNDEF = -1,
4341 };
4342
Samuel Antaoee8fb302016-01-06 13:42:12 +00004343 assert(OutlinedFn && "Invalid outlined function!");
4344
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004345 auto &Ctx = CGF.getContext();
4346
Samuel Antaobed3c462015-10-02 16:14:20 +00004347 // Fill up the arrays with the all the captured variables.
4348 SmallVector<llvm::Value *, 16> BasePointers;
4349 SmallVector<llvm::Value *, 16> Pointers;
4350 SmallVector<llvm::Value *, 16> Sizes;
4351 SmallVector<unsigned, 16> MapTypes;
4352
4353 bool hasVLACaptures = false;
4354
4355 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4356 auto RI = CS.getCapturedRecordDecl()->field_begin();
4357 // auto II = CS.capture_init_begin();
4358 auto CV = CapturedVars.begin();
4359 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
4360 CE = CS.capture_end();
4361 CI != CE; ++CI, ++RI, ++CV) {
4362 StringRef Name;
4363 QualType Ty;
4364 llvm::Value *BasePointer;
4365 llvm::Value *Pointer;
4366 llvm::Value *Size;
4367 unsigned MapType;
4368
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004369 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00004370 if (CI->capturesVariableArrayType()) {
4371 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00004372 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004373 // Copy to the device as an argument. No need to retrieve it.
4374 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00004375 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00004376 } else if (CI->capturesThis()) {
4377 BasePointer = Pointer = *CV;
4378 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004379 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004380 // Default map type.
4381 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004382 } else if (CI->capturesVariableByCopy()) {
4383 MapType = OMP_MAP_BYCOPY;
4384 if (!RI->getType()->isAnyPointerType()) {
4385 // If the field is not a pointer, we need to save the actual value and
4386 // load it as a void pointer.
4387 auto DstAddr = CGF.CreateMemTemp(
4388 Ctx.getUIntPtrType(),
4389 Twine(CI->getCapturedVar()->getName()) + ".casted");
4390 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
4391
4392 auto *SrcAddrVal = CGF.EmitScalarConversion(
4393 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
4394 Ctx.getPointerType(RI->getType()), SourceLocation());
4395 LValue SrcLV =
4396 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
4397
4398 // Store the value using the source type pointer.
4399 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
4400
4401 // Load the value using the destination type pointer.
4402 BasePointer = Pointer =
4403 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
4404 } else {
4405 MapType |= OMP_MAP_PTR;
4406 BasePointer = Pointer = *CV;
4407 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00004408 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004409 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004410 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00004411 BasePointer = Pointer = *CV;
4412
4413 const ReferenceType *PtrTy =
4414 cast<ReferenceType>(RI->getType().getTypePtr());
4415 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004416 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004417 // The default map type for a scalar/complex type is 'to' because by
4418 // default the value doesn't have to be retrieved. For an aggregate type,
4419 // the default is 'tofrom'.
4420 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
4421 : OMP_MAP_TO;
4422 if (ElementType->isAnyPointerType())
4423 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00004424 }
4425
4426 BasePointers.push_back(BasePointer);
4427 Pointers.push_back(Pointer);
4428 Sizes.push_back(Size);
4429 MapTypes.push_back(MapType);
4430 }
4431
4432 // Keep track on whether the host function has to be executed.
4433 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004434 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004435 auto OffloadError = CGF.MakeAddrLValue(
4436 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
4437 OffloadErrorQType);
4438 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
4439 OffloadError);
4440
4441 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004442 auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004443 hasVLACaptures, Device, OutlinedFnID, OffloadError,
Samuel Antaob68e2db2016-03-03 16:20:23 +00004444 OffloadErrorQType, &D](CodeGenFunction &CGF) {
Samuel Antaobed3c462015-10-02 16:14:20 +00004445 unsigned PointerNumVal = BasePointers.size();
4446 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
4447 llvm::Value *BasePointersArray;
4448 llvm::Value *PointersArray;
4449 llvm::Value *SizesArray;
4450 llvm::Value *MapTypesArray;
4451
4452 if (PointerNumVal) {
4453 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004454 QualType PointerArrayType = Ctx.getConstantArrayType(
4455 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004456 /*IndexTypeQuals=*/0);
4457
4458 BasePointersArray =
4459 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
4460 PointersArray =
4461 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
4462
4463 // If we don't have any VLA types, we can use a constant array for the map
4464 // sizes, otherwise we need to fill up the arrays as we do for the
4465 // pointers.
4466 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004467 QualType SizeArrayType = Ctx.getConstantArrayType(
4468 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004469 /*IndexTypeQuals=*/0);
4470 SizesArray =
4471 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
4472 } else {
4473 // We expect all the sizes to be constant, so we collect them to create
4474 // a constant array.
4475 SmallVector<llvm::Constant *, 16> ConstSizes;
4476 for (auto S : Sizes)
4477 ConstSizes.push_back(cast<llvm::Constant>(S));
4478
4479 auto *SizesArrayInit = llvm::ConstantArray::get(
4480 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
4481 auto *SizesArrayGbl = new llvm::GlobalVariable(
4482 CGM.getModule(), SizesArrayInit->getType(),
4483 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4484 SizesArrayInit, ".offload_sizes");
4485 SizesArrayGbl->setUnnamedAddr(true);
4486 SizesArray = SizesArrayGbl;
4487 }
4488
4489 // The map types are always constant so we don't need to generate code to
4490 // fill arrays. Instead, we create an array constant.
4491 llvm::Constant *MapTypesArrayInit =
4492 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
4493 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
4494 CGM.getModule(), MapTypesArrayInit->getType(),
4495 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4496 MapTypesArrayInit, ".offload_maptypes");
4497 MapTypesArrayGbl->setUnnamedAddr(true);
4498 MapTypesArray = MapTypesArrayGbl;
4499
4500 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004501 llvm::Value *BPVal = BasePointers[i];
4502 if (BPVal->getType()->isPointerTy())
4503 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
4504 else {
4505 assert(BPVal->getType()->isIntegerTy() &&
4506 "If not a pointer, the value type must be an integer.");
4507 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
4508 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004509 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
4510 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
4511 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004512 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4513 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004514
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004515 llvm::Value *PVal = Pointers[i];
4516 if (PVal->getType()->isPointerTy())
4517 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
4518 else {
4519 assert(PVal->getType()->isIntegerTy() &&
4520 "If not a pointer, the value type must be an integer.");
4521 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
4522 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004523 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4524 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4525 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004526 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4527 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004528
4529 if (hasVLACaptures) {
4530 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4531 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4532 /*Idx0=*/0,
4533 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004534 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004535 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4536 Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4537 SAddr);
4538 }
4539 }
4540
4541 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4542 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4543 /*Idx0=*/0, /*Idx1=*/0);
4544 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4545 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4546 /*Idx0=*/0,
4547 /*Idx1=*/0);
4548 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4549 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4550 /*Idx0=*/0, /*Idx1=*/0);
4551 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4552 llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4553 /*Idx0=*/0,
4554 /*Idx1=*/0);
4555
4556 } else {
4557 BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4558 PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4559 SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4560 MapTypesArray =
4561 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4562 }
4563
4564 // On top of the arrays that were filled up, the target offloading call
4565 // takes as arguments the device id as well as the host pointer. The host
4566 // pointer is used by the runtime library to identify the current target
4567 // region, so it only has to be unique and not necessarily point to
4568 // anything. It could be the pointer to the outlined function that
4569 // implements the target region, but we aren't using that so that the
4570 // compiler doesn't need to keep that, and could therefore inline the host
4571 // function if proven worthwhile during optimization.
4572
Samuel Antaoee8fb302016-01-06 13:42:12 +00004573 // From this point on, we need to have an ID of the target region defined.
4574 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004575
4576 // Emit device ID if any.
4577 llvm::Value *DeviceID;
4578 if (Device)
4579 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4580 CGM.Int32Ty, /*isSigned=*/true);
4581 else
4582 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4583
Samuel Antaob68e2db2016-03-03 16:20:23 +00004584 // Return value of the runtime offloading call.
4585 llvm::Value *Return;
4586
4587 auto *NumTeams = emitNumTeamsClauseForTargetDirective(*this, CGF, D);
4588 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(*this, CGF, D);
4589
4590 // If we have NumTeams defined this means that we have an enclosed teams
4591 // region. Therefore we also expect to have ThreadLimit defined. These two
4592 // values should be defined in the presence of a teams directive, regardless
4593 // of having any clauses associated. If the user is using teams but no
4594 // clauses, these two values will be the default that should be passed to
4595 // the runtime library - a 32-bit integer with the value zero.
4596 if (NumTeams) {
4597 assert(ThreadLimit && "Thread limit expression should be available along "
4598 "with number of teams.");
4599 llvm::Value *OffloadingArgs[] = {
4600 DeviceID, OutlinedFnID, PointerNum,
4601 BasePointersArray, PointersArray, SizesArray,
4602 MapTypesArray, NumTeams, ThreadLimit};
4603 Return = CGF.EmitRuntimeCall(
4604 createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
4605 } else {
4606 llvm::Value *OffloadingArgs[] = {
4607 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4608 PointersArray, SizesArray, MapTypesArray};
4609 Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4610 OffloadingArgs);
4611 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004612
4613 CGF.EmitStoreOfScalar(Return, OffloadError);
4614 };
4615
Samuel Antaoee8fb302016-01-06 13:42:12 +00004616 // Notify that the host version must be executed.
4617 auto &&ElseGen = [this, OffloadError,
4618 OffloadErrorQType](CodeGenFunction &CGF) {
4619 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4620 OffloadError);
4621 };
4622
4623 // If we have a target function ID it means that we need to support
4624 // offloading, otherwise, just execute on the host. We need to execute on host
4625 // regardless of the conditional in the if clause if, e.g., the user do not
4626 // specify target triples.
4627 if (OutlinedFnID) {
4628 if (IfCond) {
4629 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4630 } else {
4631 CodeGenFunction::RunCleanupsScope Scope(CGF);
4632 ThenGen(CGF);
4633 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004634 } else {
4635 CodeGenFunction::RunCleanupsScope Scope(CGF);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004636 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004637 }
4638
4639 // Check the error code and execute the host version if required.
4640 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4641 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4642 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4643 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4644 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4645
4646 CGF.EmitBlock(OffloadFailedBlock);
4647 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4648 CGF.EmitBranch(OffloadContBlock);
4649
4650 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004651}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004652
4653void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4654 StringRef ParentName) {
4655 if (!S)
4656 return;
4657
4658 // If we find a OMP target directive, codegen the outline function and
4659 // register the result.
4660 // FIXME: Add other directives with target when they become supported.
4661 bool isTargetDirective = isa<OMPTargetDirective>(S);
4662
4663 if (isTargetDirective) {
4664 auto *E = cast<OMPExecutableDirective>(S);
4665 unsigned DeviceID;
4666 unsigned FileID;
4667 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004668 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004669 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004670
4671 // Is this a target region that should not be emitted as an entry point? If
4672 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00004673 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4674 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004675 return;
4676
4677 llvm::Function *Fn;
4678 llvm::Constant *Addr;
4679 emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4680 /*isOffloadEntry=*/true);
4681 assert(Fn && Addr && "Target region emission failed.");
4682 return;
4683 }
4684
4685 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4686 if (!E->getAssociatedStmt())
4687 return;
4688
4689 scanForTargetRegionsFunctions(
4690 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4691 ParentName);
4692 return;
4693 }
4694
4695 // If this is a lambda function, look into its body.
4696 if (auto *L = dyn_cast<LambdaExpr>(S))
4697 S = L->getBody();
4698
4699 // Keep looking for target regions recursively.
4700 for (auto *II : S->children())
4701 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004702}
4703
4704bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4705 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4706
4707 // If emitting code for the host, we do not process FD here. Instead we do
4708 // the normal code generation.
4709 if (!CGM.getLangOpts().OpenMPIsDevice)
4710 return false;
4711
4712 // Try to detect target regions in the function.
4713 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4714
4715 // We should not emit any function othen that the ones created during the
4716 // scanning. Therefore, we signal that this function is completely dealt
4717 // with.
4718 return true;
4719}
4720
4721bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4722 if (!CGM.getLangOpts().OpenMPIsDevice)
4723 return false;
4724
4725 // Check if there are Ctors/Dtors in this declaration and look for target
4726 // regions in it. We use the complete variant to produce the kernel name
4727 // mangling.
4728 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4729 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4730 for (auto *Ctor : RD->ctors()) {
4731 StringRef ParentName =
4732 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4733 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4734 }
4735 auto *Dtor = RD->getDestructor();
4736 if (Dtor) {
4737 StringRef ParentName =
4738 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4739 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4740 }
4741 }
4742
4743 // If we are in target mode we do not emit any global (declare target is not
4744 // implemented yet). Therefore we signal that GD was processed in this case.
4745 return true;
4746}
4747
4748bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4749 auto *VD = GD.getDecl();
4750 if (isa<FunctionDecl>(VD))
4751 return emitTargetFunctions(GD);
4752
4753 return emitTargetGlobalVariable(GD);
4754}
4755
4756llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4757 // If we have offloading in the current module, we need to emit the entries
4758 // now and register the offloading descriptor.
4759 createOffloadEntriesAndInfoMetadata();
4760
4761 // Create and register the offloading binary descriptors. This is the main
4762 // entity that captures all the information about offloading in the current
4763 // compilation unit.
4764 return createOffloadingBinaryDescriptorRegistration();
4765}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004766
4767void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
4768 const OMPExecutableDirective &D,
4769 SourceLocation Loc,
4770 llvm::Value *OutlinedFn,
4771 ArrayRef<llvm::Value *> CapturedVars) {
4772 if (!CGF.HaveInsertPoint())
4773 return;
4774
4775 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4776 CodeGenFunction::RunCleanupsScope Scope(CGF);
4777
4778 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
4779 llvm::Value *Args[] = {
4780 RTLoc,
4781 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
4782 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
4783 llvm::SmallVector<llvm::Value *, 16> RealArgs;
4784 RealArgs.append(std::begin(Args), std::end(Args));
4785 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
4786
4787 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
4788 CGF.EmitRuntimeCall(RTLFn, RealArgs);
4789}
4790
4791void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
4792 llvm::Value *NumTeams,
4793 llvm::Value *ThreadLimit,
4794 SourceLocation Loc) {
4795 if (!CGF.HaveInsertPoint())
4796 return;
4797
4798 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4799
4800 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
4801 llvm::Value *PushNumTeamsArgs[] = {
4802 RTLoc, getThreadID(CGF, Loc), NumTeams, ThreadLimit};
4803 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
4804 PushNumTeamsArgs);
4805}