blob: 4637c7b77114fa4d3124be075fef66070a95b634 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "llvm/ADT/ArrayRef.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000021#include "llvm/Bitcode/ReaderWriter.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000026#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000028#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000029
30using namespace clang;
31using namespace CodeGen;
32
Benjamin Kramerc52193f2014-10-10 13:57:57 +000033namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000035class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000037 /// \brief Kinds of OpenMP regions used in codegen.
38 enum CGOpenMPRegionKind {
39 /// \brief Region with outlined function for standalone 'parallel'
40 /// directive.
41 ParallelOutlinedRegion,
42 /// \brief Region with outlined function for standalone 'task' directive.
43 TaskOutlinedRegion,
44 /// \brief Region for constructs that do not require function outlining,
45 /// like 'for', 'sections', 'atomic' etc. directives.
46 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000047 /// \brief Region with outlined function for standalone 'target' directive.
48 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 };
Alexey Bataev18095712014-10-10 12:19:54 +000050
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 CGOpenMPRegionInfo(const CapturedStmt &CS,
52 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000055 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057
58 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000061 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000063
64 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000065 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000069 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000071 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000072 /// \return LValue for thread id variable. This LValue always has type int32*.
73 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000074
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000076
Alexey Bataev81c7ea02015-07-03 09:56:58 +000077 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
78
Alexey Bataev25e5b442015-09-15 12:52:43 +000079 bool hasCancel() const { return HasCancel; }
80
Alexey Bataev18095712014-10-10 12:19:54 +000081 static bool classof(const CGCapturedStmtInfo *Info) {
82 return Info->getKind() == CR_OpenMP;
83 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000084
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000085protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000086 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000087 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000088 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000089 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090};
Alexey Bataev18095712014-10-10 12:19:54 +000091
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092/// \brief API for captured statement code generation in OpenMP constructs.
93class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
94public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000096 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +000097 OpenMPDirectiveKind Kind, bool HasCancel)
98 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
99 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
102 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000103
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000104 /// \brief Get a variable or parameter for storing global thread id
105 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000106 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000107
Alexey Bataev18095712014-10-10 12:19:54 +0000108 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000109 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000110
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000111 static bool classof(const CGCapturedStmtInfo *Info) {
112 return CGOpenMPRegionInfo::classof(Info) &&
113 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
114 ParallelOutlinedRegion;
115 }
116
Alexey Bataev18095712014-10-10 12:19:54 +0000117private:
118 /// \brief A variable or parameter storing global thread id for OpenMP
119 /// constructs.
120 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000121};
122
Alexey Bataev62b63b12015-03-10 07:28:44 +0000123/// \brief API for captured statement code generation in OpenMP constructs.
124class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
125public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000126 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000127 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000128 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000129 OpenMPDirectiveKind Kind, bool HasCancel)
130 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000131 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
133 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000134
Alexey Bataev62b63b12015-03-10 07:28:44 +0000135 /// \brief Get a variable or parameter for storing global thread id
136 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000137 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000138
139 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000140 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000141
Alexey Bataev62b63b12015-03-10 07:28:44 +0000142 /// \brief Get the name of the capture helper.
143 StringRef getHelperName() const override { return ".omp_outlined."; }
144
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000145 static bool classof(const CGCapturedStmtInfo *Info) {
146 return CGOpenMPRegionInfo::classof(Info) &&
147 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
148 TaskOutlinedRegion;
149 }
150
Alexey Bataev62b63b12015-03-10 07:28:44 +0000151private:
152 /// \brief A variable or parameter storing global thread id for OpenMP
153 /// constructs.
154 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000155};
156
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000157/// \brief API for inlined captured statement code generation in OpenMP
158/// constructs.
159class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
160public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000161 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000162 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000163 OpenMPDirectiveKind Kind, bool HasCancel)
164 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
165 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000166 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000167
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000168 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000169 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000170 if (OuterRegionInfo)
171 return OuterRegionInfo->getContextValue();
172 llvm_unreachable("No context value for inlined OpenMP region");
173 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000174
Hans Wennborg7eb54642015-09-10 17:07:54 +0000175 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000176 if (OuterRegionInfo) {
177 OuterRegionInfo->setContextValue(V);
178 return;
179 }
180 llvm_unreachable("No context value for inlined OpenMP region");
181 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000182
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000183 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000184 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 if (OuterRegionInfo)
186 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000187 // If there is no outer outlined region,no need to lookup in a list of
188 // captured variables, we can use the original one.
189 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000190 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000191
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000193 if (OuterRegionInfo)
194 return OuterRegionInfo->getThisFieldDecl();
195 return nullptr;
196 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000197
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000198 /// \brief Get a variable or parameter for storing global thread id
199 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000200 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000201 if (OuterRegionInfo)
202 return OuterRegionInfo->getThreadIDVariable();
203 return nullptr;
204 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000205
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000206 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000207 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000208 if (auto *OuterRegionInfo = getOldCSI())
209 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000210 llvm_unreachable("No helper name for inlined OpenMP construct");
211 }
212
213 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
214
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000215 static bool classof(const CGCapturedStmtInfo *Info) {
216 return CGOpenMPRegionInfo::classof(Info) &&
217 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
218 }
219
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000220private:
221 /// \brief CodeGen info about outer OpenMP region.
222 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
223 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000224};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225
Samuel Antaobed3c462015-10-02 16:14:20 +0000226/// \brief API for captured statement code generation in OpenMP target
227/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000228/// captured fields. The name of the target region has to be unique in a given
229/// application so it is provided by the client, because only the client has
230/// the information to generate that.
Samuel Antaobed3c462015-10-02 16:14:20 +0000231class CGOpenMPTargetRegionInfo : public CGOpenMPRegionInfo {
232public:
233 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000234 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000235 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000236 /*HasCancel=*/false),
237 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000238
239 /// \brief This is unused for target regions because each starts executing
240 /// with a single thread.
241 const VarDecl *getThreadIDVariable() const override { return nullptr; }
242
243 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000244 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000245
246 static bool classof(const CGCapturedStmtInfo *Info) {
247 return CGOpenMPRegionInfo::classof(Info) &&
248 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
249 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000250
251private:
252 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000253};
254
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000255/// \brief RAII for emitting code of OpenMP constructs.
256class InlinedOpenMPRegionRAII {
257 CodeGenFunction &CGF;
258
259public:
260 /// \brief Constructs region for combined constructs.
261 /// \param CodeGen Code generation sequence for combined directives. Includes
262 /// a list of functions used for code generation of implicitly inlined
263 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000264 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000265 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000266 : CGF(CGF) {
267 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000268 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
269 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000270 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000271
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000272 ~InlinedOpenMPRegionRAII() {
273 // Restore original CapturedStmtInfo only if we're done with code emission.
274 auto *OldCSI =
275 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
276 delete CGF.CapturedStmtInfo;
277 CGF.CapturedStmtInfo = OldCSI;
278 }
279};
280
Hans Wennborg7eb54642015-09-10 17:07:54 +0000281} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000282
283LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000284 return CGF.EmitLoadOfPointerLValue(
285 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
286 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000287}
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000290 if (!CGF.HaveInsertPoint())
291 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000292 // 1.2.2 OpenMP Language Terminology
293 // Structured block - An executable statement with a single entry at the
294 // top and a single exit at the bottom.
295 // The point of exit cannot be a branch out of the structured block.
296 // longjmp() and throw() must not violate the entry/exit criteria.
297 CGF.EHStack.pushTerminate();
298 {
299 CodeGenFunction::RunCleanupsScope Scope(CGF);
300 CodeGen(CGF);
301 }
302 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000303}
304
Alexey Bataev62b63b12015-03-10 07:28:44 +0000305LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
306 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000307 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
308 getThreadIDVariable()->getType(),
309 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000310}
311
Alexey Bataev9959db52014-05-06 10:08:46 +0000312CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Samuel Antaoee8fb302016-01-06 13:42:12 +0000313 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr),
314 OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000315 IdentTy = llvm::StructType::create(
316 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
317 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000318 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000319 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000320 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
321 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000322 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000323 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000324
325 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000326}
327
Alexey Bataev91797552015-03-18 04:13:55 +0000328void CGOpenMPRuntime::clear() {
329 InternalVars.clear();
330}
331
John McCall7f416cc2015-09-08 08:05:57 +0000332// Layout information for ident_t.
333static CharUnits getIdentAlign(CodeGenModule &CGM) {
334 return CGM.getPointerAlign();
335}
336static CharUnits getIdentSize(CodeGenModule &CGM) {
337 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
338 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
339}
340static CharUnits getOffsetOfIdentField(CGOpenMPRuntime::IdentFieldIndex Field) {
341 // All the fields except the last are i32, so this works beautifully.
342 return unsigned(Field) * CharUnits::fromQuantity(4);
343}
344static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
345 CGOpenMPRuntime::IdentFieldIndex Field,
346 const llvm::Twine &Name = "") {
347 auto Offset = getOffsetOfIdentField(Field);
348 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
349}
350
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000351llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
352 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
353 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000354 assert(ThreadIDVar->getType()->isPointerType() &&
355 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000356 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
357 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000358 bool HasCancel = false;
359 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
360 HasCancel = OPD->hasCancel();
361 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
362 HasCancel = OPSD->hasCancel();
363 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
364 HasCancel = OPFD->hasCancel();
365 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
366 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000367 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000368 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000369}
370
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000371llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
372 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
373 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000374 assert(!ThreadIDVar->getType()->isPointerType() &&
375 "thread id variable must be of type kmp_int32 for tasks");
376 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
377 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000378 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000379 InnermostKind,
380 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000381 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000382 return CGF.GenerateCapturedStmtFunction(*CS);
383}
384
John McCall7f416cc2015-09-08 08:05:57 +0000385Address CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
386 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000387 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000388 if (!Entry) {
389 if (!DefaultOpenMPPSource) {
390 // Initialize default location for psource field of ident_t structure of
391 // all ident_t objects. Format is ";file;function;line;column;;".
392 // Taken from
393 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
394 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000395 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000396 DefaultOpenMPPSource =
397 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
398 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000399 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
400 CGM.getModule(), IdentTy, /*isConstant*/ true,
401 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000402 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000403 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000404
405 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000406 llvm::Constant *Values[] = {Zero,
407 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
408 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000409 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
410 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000411 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000412 }
John McCall7f416cc2015-09-08 08:05:57 +0000413 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000414}
415
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000416llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
417 SourceLocation Loc,
418 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000419 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000420 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000421 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000422 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000423
424 assert(CGF.CurFn && "No function in current CodeGenFunction.");
425
John McCall7f416cc2015-09-08 08:05:57 +0000426 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000427 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
428 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000429 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
430
Alexander Musmanc6388682014-12-15 07:07:06 +0000431 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
432 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000433 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000434 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000435 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
436 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000437 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000438 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000439 LocValue = AI;
440
441 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
442 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000443 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000444 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000445 }
446
447 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000448 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000449
Alexey Bataevf002aca2014-05-30 05:48:40 +0000450 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
451 if (OMPDebugLoc == nullptr) {
452 SmallString<128> Buffer2;
453 llvm::raw_svector_ostream OS2(Buffer2);
454 // Build debug location
455 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
456 OS2 << ";" << PLoc.getFilename() << ";";
457 if (const FunctionDecl *FD =
458 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
459 OS2 << FD->getQualifiedNameAsString();
460 }
461 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
462 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
463 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000464 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000465 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000466 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
467
John McCall7f416cc2015-09-08 08:05:57 +0000468 // Our callers always pass this to a runtime function, so for
469 // convenience, go ahead and return a naked pointer.
470 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000471}
472
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000473llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
474 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000475 assert(CGF.CurFn && "No function in current CodeGenFunction.");
476
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000477 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000478 // Check whether we've already cached a load of the thread id in this
479 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000480 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000481 if (I != OpenMPLocThreadIDMap.end()) {
482 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000483 if (ThreadID != nullptr)
484 return ThreadID;
485 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000486 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000487 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000488 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000489 // Check if this an outlined function with thread id passed as argument.
490 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000491 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
492 // If value loaded in entry block, cache it and use it everywhere in
493 // function.
494 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
495 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
496 Elem.second.ThreadID = ThreadID;
497 }
498 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000499 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000500 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000501
502 // This is not an outlined function region - need to call __kmpc_int32
503 // kmpc_global_thread_num(ident_t *loc).
504 // Generate thread id value and cache this value for use across the
505 // function.
506 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
507 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
508 ThreadID =
509 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
510 emitUpdateLocation(CGF, Loc));
511 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
512 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000513 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000514}
515
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000516void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000517 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000518 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
519 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000520}
521
522llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
523 return llvm::PointerType::getUnqual(IdentTy);
524}
525
526llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
527 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
528}
529
530llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000531CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000532 llvm::Constant *RTLFn = nullptr;
533 switch (Function) {
534 case OMPRTL__kmpc_fork_call: {
535 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
536 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000537 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
538 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000539 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000540 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000541 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
542 break;
543 }
544 case OMPRTL__kmpc_global_thread_num: {
545 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000546 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000547 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000548 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000549 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
550 break;
551 }
Alexey Bataev97720002014-11-11 04:05:39 +0000552 case OMPRTL__kmpc_threadprivate_cached: {
553 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
554 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
555 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
556 CGM.VoidPtrTy, CGM.SizeTy,
557 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
558 llvm::FunctionType *FnTy =
559 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
560 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
561 break;
562 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000563 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000564 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
565 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000566 llvm::Type *TypeParams[] = {
567 getIdentTyPointerTy(), CGM.Int32Ty,
568 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
569 llvm::FunctionType *FnTy =
570 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
571 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
572 break;
573 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000574 case OMPRTL__kmpc_critical_with_hint: {
575 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
576 // kmp_critical_name *crit, uintptr_t hint);
577 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
578 llvm::PointerType::getUnqual(KmpCriticalNameTy),
579 CGM.IntPtrTy};
580 llvm::FunctionType *FnTy =
581 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
582 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
583 break;
584 }
Alexey Bataev97720002014-11-11 04:05:39 +0000585 case OMPRTL__kmpc_threadprivate_register: {
586 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
587 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
588 // typedef void *(*kmpc_ctor)(void *);
589 auto KmpcCtorTy =
590 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
591 /*isVarArg*/ false)->getPointerTo();
592 // typedef void *(*kmpc_cctor)(void *, void *);
593 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
594 auto KmpcCopyCtorTy =
595 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
596 /*isVarArg*/ false)->getPointerTo();
597 // typedef void (*kmpc_dtor)(void *);
598 auto KmpcDtorTy =
599 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
600 ->getPointerTo();
601 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
602 KmpcCopyCtorTy, KmpcDtorTy};
603 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
604 /*isVarArg*/ false);
605 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
606 break;
607 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000608 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000609 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
610 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000611 llvm::Type *TypeParams[] = {
612 getIdentTyPointerTy(), CGM.Int32Ty,
613 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
614 llvm::FunctionType *FnTy =
615 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
616 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
617 break;
618 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000619 case OMPRTL__kmpc_cancel_barrier: {
620 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
621 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000622 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
623 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000624 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
625 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000626 break;
627 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000628 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000629 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000630 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
631 llvm::FunctionType *FnTy =
632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
633 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
634 break;
635 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000636 case OMPRTL__kmpc_for_static_fini: {
637 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
638 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
639 llvm::FunctionType *FnTy =
640 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
641 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
642 break;
643 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000644 case OMPRTL__kmpc_push_num_threads: {
645 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
646 // kmp_int32 num_threads)
647 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
648 CGM.Int32Ty};
649 llvm::FunctionType *FnTy =
650 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
652 break;
653 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000654 case OMPRTL__kmpc_serialized_parallel: {
655 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
656 // global_tid);
657 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
658 llvm::FunctionType *FnTy =
659 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
660 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
661 break;
662 }
663 case OMPRTL__kmpc_end_serialized_parallel: {
664 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
665 // global_tid);
666 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
667 llvm::FunctionType *FnTy =
668 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
669 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
670 break;
671 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000672 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000673 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000674 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
675 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000676 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000677 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
678 break;
679 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000680 case OMPRTL__kmpc_master: {
681 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
682 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
683 llvm::FunctionType *FnTy =
684 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
685 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
686 break;
687 }
688 case OMPRTL__kmpc_end_master: {
689 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
690 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
691 llvm::FunctionType *FnTy =
692 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
693 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
694 break;
695 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000696 case OMPRTL__kmpc_omp_taskyield: {
697 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
698 // int end_part);
699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
700 llvm::FunctionType *FnTy =
701 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
702 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
703 break;
704 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000705 case OMPRTL__kmpc_single: {
706 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
707 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
708 llvm::FunctionType *FnTy =
709 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
710 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
711 break;
712 }
713 case OMPRTL__kmpc_end_single: {
714 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
715 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
716 llvm::FunctionType *FnTy =
717 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
718 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
719 break;
720 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000721 case OMPRTL__kmpc_omp_task_alloc: {
722 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
723 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
724 // kmp_routine_entry_t *task_entry);
725 assert(KmpRoutineEntryPtrTy != nullptr &&
726 "Type kmp_routine_entry_t must be created.");
727 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
728 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
729 // Return void * and then cast to particular kmp_task_t type.
730 llvm::FunctionType *FnTy =
731 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
732 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
733 break;
734 }
735 case OMPRTL__kmpc_omp_task: {
736 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
737 // *new_task);
738 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
739 CGM.VoidPtrTy};
740 llvm::FunctionType *FnTy =
741 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
743 break;
744 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000745 case OMPRTL__kmpc_copyprivate: {
746 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +0000747 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +0000748 // kmp_int32 didit);
749 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
750 auto *CpyFnTy =
751 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +0000752 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +0000753 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
754 CGM.Int32Ty};
755 llvm::FunctionType *FnTy =
756 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
757 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
758 break;
759 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000760 case OMPRTL__kmpc_reduce: {
761 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
762 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
763 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
764 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
765 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
766 /*isVarArg=*/false);
767 llvm::Type *TypeParams[] = {
768 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
769 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
770 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
771 llvm::FunctionType *FnTy =
772 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
773 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
774 break;
775 }
776 case OMPRTL__kmpc_reduce_nowait: {
777 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
778 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
779 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
780 // *lck);
781 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
782 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
783 /*isVarArg=*/false);
784 llvm::Type *TypeParams[] = {
785 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
786 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
787 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
788 llvm::FunctionType *FnTy =
789 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
790 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
791 break;
792 }
793 case OMPRTL__kmpc_end_reduce: {
794 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
795 // kmp_critical_name *lck);
796 llvm::Type *TypeParams[] = {
797 getIdentTyPointerTy(), CGM.Int32Ty,
798 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
799 llvm::FunctionType *FnTy =
800 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
801 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
802 break;
803 }
804 case OMPRTL__kmpc_end_reduce_nowait: {
805 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
806 // kmp_critical_name *lck);
807 llvm::Type *TypeParams[] = {
808 getIdentTyPointerTy(), CGM.Int32Ty,
809 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
810 llvm::FunctionType *FnTy =
811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
812 RTLFn =
813 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
814 break;
815 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000816 case OMPRTL__kmpc_omp_task_begin_if0: {
817 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
818 // *new_task);
819 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
820 CGM.VoidPtrTy};
821 llvm::FunctionType *FnTy =
822 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
823 RTLFn =
824 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
825 break;
826 }
827 case OMPRTL__kmpc_omp_task_complete_if0: {
828 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
829 // *new_task);
830 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
831 CGM.VoidPtrTy};
832 llvm::FunctionType *FnTy =
833 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
834 RTLFn = CGM.CreateRuntimeFunction(FnTy,
835 /*Name=*/"__kmpc_omp_task_complete_if0");
836 break;
837 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000838 case OMPRTL__kmpc_ordered: {
839 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
840 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
841 llvm::FunctionType *FnTy =
842 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
843 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
844 break;
845 }
846 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000847 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000848 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
849 llvm::FunctionType *FnTy =
850 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
851 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
852 break;
853 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +0000854 case OMPRTL__kmpc_omp_taskwait: {
855 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
856 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
857 llvm::FunctionType *FnTy =
858 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
859 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
860 break;
861 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000862 case OMPRTL__kmpc_taskgroup: {
863 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
864 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
865 llvm::FunctionType *FnTy =
866 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
867 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
868 break;
869 }
870 case OMPRTL__kmpc_end_taskgroup: {
871 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
872 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
873 llvm::FunctionType *FnTy =
874 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
875 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
876 break;
877 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000878 case OMPRTL__kmpc_push_proc_bind: {
879 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
880 // int proc_bind)
881 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
882 llvm::FunctionType *FnTy =
883 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
884 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
885 break;
886 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +0000887 case OMPRTL__kmpc_omp_task_with_deps: {
888 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
889 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
890 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
891 llvm::Type *TypeParams[] = {
892 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
893 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
894 llvm::FunctionType *FnTy =
895 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
896 RTLFn =
897 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
898 break;
899 }
900 case OMPRTL__kmpc_omp_wait_deps: {
901 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
902 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
903 // kmp_depend_info_t *noalias_dep_list);
904 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
905 CGM.Int32Ty, CGM.VoidPtrTy,
906 CGM.Int32Ty, CGM.VoidPtrTy};
907 llvm::FunctionType *FnTy =
908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
909 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
910 break;
911 }
Alexey Bataev0f34da12015-07-02 04:17:07 +0000912 case OMPRTL__kmpc_cancellationpoint: {
913 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
914 // global_tid, kmp_int32 cncl_kind)
915 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
916 llvm::FunctionType *FnTy =
917 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
918 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
919 break;
920 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000921 case OMPRTL__kmpc_cancel: {
922 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
923 // kmp_int32 cncl_kind)
924 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
925 llvm::FunctionType *FnTy =
926 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
927 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
928 break;
929 }
Samuel Antaobed3c462015-10-02 16:14:20 +0000930 case OMPRTL__tgt_target: {
931 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
932 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
933 // *arg_types);
934 llvm::Type *TypeParams[] = {CGM.Int32Ty,
935 CGM.VoidPtrTy,
936 CGM.Int32Ty,
937 CGM.VoidPtrPtrTy,
938 CGM.VoidPtrPtrTy,
939 CGM.SizeTy->getPointerTo(),
940 CGM.Int32Ty->getPointerTo()};
941 llvm::FunctionType *FnTy =
942 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
943 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
944 break;
945 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000946 case OMPRTL__tgt_register_lib: {
947 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
948 QualType ParamTy =
949 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
950 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
951 llvm::FunctionType *FnTy =
952 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
953 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
954 break;
955 }
956 case OMPRTL__tgt_unregister_lib: {
957 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
958 QualType ParamTy =
959 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
960 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
961 llvm::FunctionType *FnTy =
962 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
963 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
964 break;
965 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000966 }
967 return RTLFn;
968}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000969
Alexander Musman21212e42015-03-13 10:38:23 +0000970llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
971 bool IVSigned) {
972 assert((IVSize == 32 || IVSize == 64) &&
973 "IV size is not compatible with the omp runtime");
974 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
975 : "__kmpc_for_static_init_4u")
976 : (IVSigned ? "__kmpc_for_static_init_8"
977 : "__kmpc_for_static_init_8u");
978 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
979 auto PtrTy = llvm::PointerType::getUnqual(ITy);
980 llvm::Type *TypeParams[] = {
981 getIdentTyPointerTy(), // loc
982 CGM.Int32Ty, // tid
983 CGM.Int32Ty, // schedtype
984 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
985 PtrTy, // p_lower
986 PtrTy, // p_upper
987 PtrTy, // p_stride
988 ITy, // incr
989 ITy // chunk
990 };
991 llvm::FunctionType *FnTy =
992 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
993 return CGM.CreateRuntimeFunction(FnTy, Name);
994}
995
Alexander Musman92bdaab2015-03-12 13:37:50 +0000996llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
997 bool IVSigned) {
998 assert((IVSize == 32 || IVSize == 64) &&
999 "IV size is not compatible with the omp runtime");
1000 auto Name =
1001 IVSize == 32
1002 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1003 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1004 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1005 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1006 CGM.Int32Ty, // tid
1007 CGM.Int32Ty, // schedtype
1008 ITy, // lower
1009 ITy, // upper
1010 ITy, // stride
1011 ITy // chunk
1012 };
1013 llvm::FunctionType *FnTy =
1014 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1015 return CGM.CreateRuntimeFunction(FnTy, Name);
1016}
1017
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001018llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1019 bool IVSigned) {
1020 assert((IVSize == 32 || IVSize == 64) &&
1021 "IV size is not compatible with the omp runtime");
1022 auto Name =
1023 IVSize == 32
1024 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1025 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1026 llvm::Type *TypeParams[] = {
1027 getIdentTyPointerTy(), // loc
1028 CGM.Int32Ty, // tid
1029 };
1030 llvm::FunctionType *FnTy =
1031 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1032 return CGM.CreateRuntimeFunction(FnTy, Name);
1033}
1034
Alexander Musman92bdaab2015-03-12 13:37:50 +00001035llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1036 bool IVSigned) {
1037 assert((IVSize == 32 || IVSize == 64) &&
1038 "IV size is not compatible with the omp runtime");
1039 auto Name =
1040 IVSize == 32
1041 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1042 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1043 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1044 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1045 llvm::Type *TypeParams[] = {
1046 getIdentTyPointerTy(), // loc
1047 CGM.Int32Ty, // tid
1048 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1049 PtrTy, // p_lower
1050 PtrTy, // p_upper
1051 PtrTy // p_stride
1052 };
1053 llvm::FunctionType *FnTy =
1054 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1055 return CGM.CreateRuntimeFunction(FnTy, Name);
1056}
1057
Alexey Bataev97720002014-11-11 04:05:39 +00001058llvm::Constant *
1059CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001060 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1061 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001062 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001063 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001064 Twine(CGM.getMangledName(VD)) + ".cache.");
1065}
1066
John McCall7f416cc2015-09-08 08:05:57 +00001067Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1068 const VarDecl *VD,
1069 Address VDAddr,
1070 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001071 if (CGM.getLangOpts().OpenMPUseTLS &&
1072 CGM.getContext().getTargetInfo().isTLSSupported())
1073 return VDAddr;
1074
John McCall7f416cc2015-09-08 08:05:57 +00001075 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001076 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001077 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1078 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001079 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1080 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001081 return Address(CGF.EmitRuntimeCall(
1082 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1083 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001084}
1085
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001086void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001087 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001088 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1089 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1090 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001091 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1092 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001093 OMPLoc);
1094 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1095 // to register constructor/destructor for variable.
1096 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001097 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1098 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001099 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001100 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001101 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001102}
1103
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001104llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001105 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001106 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001107 if (CGM.getLangOpts().OpenMPUseTLS &&
1108 CGM.getContext().getTargetInfo().isTLSSupported())
1109 return nullptr;
1110
Alexey Bataev97720002014-11-11 04:05:39 +00001111 VD = VD->getDefinition(CGM.getContext());
1112 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1113 ThreadPrivateWithDefinition.insert(VD);
1114 QualType ASTTy = VD->getType();
1115
1116 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1117 auto Init = VD->getAnyInitializer();
1118 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1119 // Generate function that re-emits the declaration's initializer into the
1120 // threadprivate copy of the variable VD
1121 CodeGenFunction CtorCGF(CGM);
1122 FunctionArgList Args;
1123 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1124 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1125 Args.push_back(&Dst);
1126
1127 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1128 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1129 /*isVariadic=*/false);
1130 auto FTy = CGM.getTypes().GetFunctionType(FI);
1131 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001132 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001133 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1134 Args, SourceLocation());
1135 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001136 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001137 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001138 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1139 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1140 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001141 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1142 /*IsInitializer=*/true);
1143 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001144 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001145 CGM.getContext().VoidPtrTy, Dst.getLocation());
1146 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1147 CtorCGF.FinishFunction();
1148 Ctor = Fn;
1149 }
1150 if (VD->getType().isDestructedType() != QualType::DK_none) {
1151 // Generate function that emits destructor call for the threadprivate copy
1152 // of the variable VD
1153 CodeGenFunction DtorCGF(CGM);
1154 FunctionArgList Args;
1155 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1156 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1157 Args.push_back(&Dst);
1158
1159 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1160 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1161 /*isVariadic=*/false);
1162 auto FTy = CGM.getTypes().GetFunctionType(FI);
1163 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001164 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001165 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1166 SourceLocation());
1167 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1168 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001169 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1170 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001171 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1172 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1173 DtorCGF.FinishFunction();
1174 Dtor = Fn;
1175 }
1176 // Do not emit init function if it is not required.
1177 if (!Ctor && !Dtor)
1178 return nullptr;
1179
1180 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1181 auto CopyCtorTy =
1182 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1183 /*isVarArg=*/false)->getPointerTo();
1184 // Copying constructor for the threadprivate variable.
1185 // Must be NULL - reserved by runtime, but currently it requires that this
1186 // parameter is always NULL. Otherwise it fires assertion.
1187 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1188 if (Ctor == nullptr) {
1189 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1190 /*isVarArg=*/false)->getPointerTo();
1191 Ctor = llvm::Constant::getNullValue(CtorTy);
1192 }
1193 if (Dtor == nullptr) {
1194 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1195 /*isVarArg=*/false)->getPointerTo();
1196 Dtor = llvm::Constant::getNullValue(DtorTy);
1197 }
1198 if (!CGF) {
1199 auto InitFunctionTy =
1200 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1201 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001202 InitFunctionTy, ".__omp_threadprivate_init_.",
1203 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001204 CodeGenFunction InitCGF(CGM);
1205 FunctionArgList ArgList;
1206 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1207 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1208 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001209 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001210 InitCGF.FinishFunction();
1211 return InitFunction;
1212 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001213 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001214 }
1215 return nullptr;
1216}
1217
Alexey Bataev1d677132015-04-22 13:57:31 +00001218/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1219/// function. Here is the logic:
1220/// if (Cond) {
1221/// ThenGen();
1222/// } else {
1223/// ElseGen();
1224/// }
1225static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1226 const RegionCodeGenTy &ThenGen,
1227 const RegionCodeGenTy &ElseGen) {
1228 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1229
1230 // If the condition constant folds and can be elided, try to avoid emitting
1231 // the condition and the dead arm of the if/else.
1232 bool CondConstant;
1233 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1234 CodeGenFunction::RunCleanupsScope Scope(CGF);
1235 if (CondConstant) {
1236 ThenGen(CGF);
1237 } else {
1238 ElseGen(CGF);
1239 }
1240 return;
1241 }
1242
1243 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1244 // emit the conditional branch.
1245 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1246 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1247 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1248 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1249
1250 // Emit the 'then' code.
1251 CGF.EmitBlock(ThenBlock);
1252 {
1253 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1254 ThenGen(CGF);
1255 }
1256 CGF.EmitBranch(ContBlock);
1257 // Emit the 'else' code if present.
1258 {
1259 // There is no need to emit line number for unconditional branch.
1260 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1261 CGF.EmitBlock(ElseBlock);
1262 }
1263 {
1264 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1265 ElseGen(CGF);
1266 }
1267 {
1268 // There is no need to emit line number for unconditional branch.
1269 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1270 CGF.EmitBranch(ContBlock);
1271 }
1272 // Emit the continuation block for code after the if.
1273 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001274}
1275
Alexey Bataev1d677132015-04-22 13:57:31 +00001276void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1277 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001278 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001279 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001280 if (!CGF.HaveInsertPoint())
1281 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001282 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001283 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1284 RTLoc](CodeGenFunction &CGF) {
1285 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1286 llvm::Value *Args[] = {
1287 RTLoc,
1288 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1289 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1290 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1291 RealArgs.append(std::begin(Args), std::end(Args));
1292 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1293
1294 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1295 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1296 };
1297 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1298 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001299 auto ThreadID = getThreadID(CGF, Loc);
1300 // Build calls:
1301 // __kmpc_serialized_parallel(&Loc, GTid);
1302 llvm::Value *Args[] = {RTLoc, ThreadID};
1303 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1304 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001305
Alexey Bataev1d677132015-04-22 13:57:31 +00001306 // OutlinedFn(&GTid, &zero, CapturedStruct);
1307 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001308 Address ZeroAddr =
1309 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1310 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001311 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001312 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1313 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1314 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1315 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001316 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001317
Alexey Bataev1d677132015-04-22 13:57:31 +00001318 // __kmpc_end_serialized_parallel(&Loc, GTid);
1319 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1320 CGF.EmitRuntimeCall(
1321 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1322 };
1323 if (IfCond) {
1324 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1325 } else {
1326 CodeGenFunction::RunCleanupsScope Scope(CGF);
1327 ThenGen(CGF);
1328 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001329}
1330
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001331// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001332// thread-ID variable (it is passed in a first argument of the outlined function
1333// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1334// regular serial code region, get thread ID by calling kmp_int32
1335// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1336// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001337Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1338 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001339 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001340 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001341 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001342 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001343
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001344 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001345 auto Int32Ty =
1346 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1347 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1348 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001349 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001350
1351 return ThreadIDTemp;
1352}
1353
Alexey Bataev97720002014-11-11 04:05:39 +00001354llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001355CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001356 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001357 SmallString<256> Buffer;
1358 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001359 Out << Name;
1360 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001361 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1362 if (Elem.second) {
1363 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001364 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001365 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001366 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001367
David Blaikie13156b62014-11-19 03:06:06 +00001368 return Elem.second = new llvm::GlobalVariable(
1369 CGM.getModule(), Ty, /*IsConstant*/ false,
1370 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1371 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001372}
1373
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001374llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001375 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001376 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001377}
1378
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001379namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001380template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001381 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001382 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001383
1384public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001385 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1386 : Callee(Callee) {
1387 assert(CleanupArgs.size() == N);
1388 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1389 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001390
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001391 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001392 if (!CGF.HaveInsertPoint())
1393 return;
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001394 CGF.EmitRuntimeCall(Callee, Args);
1395 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001396};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001397} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001398
1399void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1400 StringRef CriticalName,
1401 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001402 SourceLocation Loc, const Expr *Hint) {
1403 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001404 // CriticalOpGen();
1405 // __kmpc_end_critical(ident_t *, gtid, Lock);
1406 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001407 if (!CGF.HaveInsertPoint())
1408 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001409 CodeGenFunction::RunCleanupsScope Scope(CGF);
1410 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1411 getCriticalRegionLock(CriticalName)};
1412 if (Hint) {
1413 llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1414 std::end(Args));
1415 auto *HintVal = CGF.EmitScalarExpr(Hint);
1416 ArgsWithHint.push_back(
1417 CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1418 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1419 ArgsWithHint);
1420 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001421 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001422 // Build a call to __kmpc_end_critical
1423 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1424 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1425 llvm::makeArrayRef(Args));
1426 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001427}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001428
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001429static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001430 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001431 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001432 llvm::Value *CallBool = CGF.EmitScalarConversion(
1433 IfCond,
1434 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001435 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001436
1437 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1438 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1439 // Generate the branch (If-stmt)
1440 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1441 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001442 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001443 // Emit the rest of bblocks/branches
1444 CGF.EmitBranch(ContBlock);
1445 CGF.EmitBlock(ContBlock, true);
1446}
1447
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001448void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001449 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001450 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001451 if (!CGF.HaveInsertPoint())
1452 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001453 // if(__kmpc_master(ident_t *, gtid)) {
1454 // MasterOpGen();
1455 // __kmpc_end_master(ident_t *, gtid);
1456 // }
1457 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001458 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001459 auto *IsMaster =
1460 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001461 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1462 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001463 emitIfStmt(
1464 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1465 CodeGenFunction::RunCleanupsScope Scope(CGF);
1466 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1467 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1468 llvm::makeArrayRef(Args));
1469 MasterOpGen(CGF);
1470 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001471}
1472
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001473void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1474 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001475 if (!CGF.HaveInsertPoint())
1476 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001477 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1478 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001479 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001480 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001481 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001482}
1483
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001484void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1485 const RegionCodeGenTy &TaskgroupOpGen,
1486 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001487 if (!CGF.HaveInsertPoint())
1488 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001489 // __kmpc_taskgroup(ident_t *, gtid);
1490 // TaskgroupOpGen();
1491 // __kmpc_end_taskgroup(ident_t *, gtid);
1492 // Prepare arguments and build a call to __kmpc_taskgroup
1493 {
1494 CodeGenFunction::RunCleanupsScope Scope(CGF);
1495 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1496 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1497 // Build a call to __kmpc_end_taskgroup
1498 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1499 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1500 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001501 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001502 }
1503}
1504
John McCall7f416cc2015-09-08 08:05:57 +00001505/// Given an array of pointers to variables, project the address of a
1506/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001507static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1508 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001509 // Pull out the pointer to the variable.
1510 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001511 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001512 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1513
1514 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001515 Addr = CGF.Builder.CreateElementBitCast(
1516 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001517 return Addr;
1518}
1519
Alexey Bataeva63048e2015-03-23 06:18:07 +00001520static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001521 CodeGenModule &CGM, llvm::Type *ArgsType,
1522 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1523 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001524 auto &C = CGM.getContext();
1525 // void copy_func(void *LHSArg, void *RHSArg);
1526 FunctionArgList Args;
1527 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1528 C.VoidPtrTy);
1529 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1530 C.VoidPtrTy);
1531 Args.push_back(&LHSArg);
1532 Args.push_back(&RHSArg);
1533 FunctionType::ExtInfo EI;
1534 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1535 C.VoidTy, Args, EI, /*isVariadic=*/false);
1536 auto *Fn = llvm::Function::Create(
1537 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1538 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001539 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001540 CodeGenFunction CGF(CGM);
1541 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001542 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001543 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001544 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1545 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1546 ArgsType), CGF.getPointerAlign());
1547 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1548 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1549 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001550 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1551 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1552 // ...
1553 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001554 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001555 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1556 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1557
1558 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1559 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1560
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001561 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1562 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001563 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001564 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001565 CGF.FinishFunction();
1566 return Fn;
1567}
1568
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001569void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001570 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001571 SourceLocation Loc,
1572 ArrayRef<const Expr *> CopyprivateVars,
1573 ArrayRef<const Expr *> SrcExprs,
1574 ArrayRef<const Expr *> DstExprs,
1575 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001576 if (!CGF.HaveInsertPoint())
1577 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001578 assert(CopyprivateVars.size() == SrcExprs.size() &&
1579 CopyprivateVars.size() == DstExprs.size() &&
1580 CopyprivateVars.size() == AssignmentOps.size());
1581 auto &C = CGM.getContext();
1582 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001583 // if(__kmpc_single(ident_t *, gtid)) {
1584 // SingleOpGen();
1585 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001586 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001587 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001588 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1589 // <copy_func>, did_it);
1590
John McCall7f416cc2015-09-08 08:05:57 +00001591 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001592 if (!CopyprivateVars.empty()) {
1593 // int32 did_it = 0;
1594 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1595 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00001596 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001597 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001598 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001599 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001600 auto *IsSingle =
1601 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001602 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1603 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001604 emitIfStmt(
1605 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
1606 CodeGenFunction::RunCleanupsScope Scope(CGF);
1607 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
1608 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1609 llvm::makeArrayRef(Args));
1610 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001611 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001612 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00001613 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001614 }
1615 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001616 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1617 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00001618 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001619 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1620 auto CopyprivateArrayTy =
1621 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1622 /*IndexTypeQuals=*/0);
1623 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00001624 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001625 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1626 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001627 Address Elem = CGF.Builder.CreateConstArrayGEP(
1628 CopyprivateList, I, CGF.getPointerSize());
1629 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00001630 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001631 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
1632 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001633 }
1634 // Build function that copies private values from single region to all other
1635 // threads in the corresponding parallel region.
1636 auto *CpyFn = emitCopyprivateCopyFunction(
1637 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001638 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001639 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00001640 Address CL =
1641 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1642 CGF.VoidPtrTy);
1643 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001644 llvm::Value *Args[] = {
1645 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1646 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001647 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00001648 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001649 CpyFn, // void (*) (void *, void *) <copy_func>
1650 DidItVal // i32 did_it
1651 };
1652 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1653 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001654}
1655
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001656void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1657 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00001658 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001659 if (!CGF.HaveInsertPoint())
1660 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001661 // __kmpc_ordered(ident_t *, gtid);
1662 // OrderedOpGen();
1663 // __kmpc_end_ordered(ident_t *, gtid);
1664 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00001665 CodeGenFunction::RunCleanupsScope Scope(CGF);
1666 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001667 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1668 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1669 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001670 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001671 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1672 llvm::makeArrayRef(Args));
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001673 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00001674 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001675}
1676
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001677void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001678 OpenMPDirectiveKind Kind, bool EmitChecks,
1679 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001680 if (!CGF.HaveInsertPoint())
1681 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001682 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001683 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001684 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1685 if (Kind == OMPD_for) {
1686 Flags =
1687 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1688 } else if (Kind == OMPD_sections) {
1689 Flags = static_cast<OpenMPLocationFlags>(Flags |
1690 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1691 } else if (Kind == OMPD_single) {
1692 Flags =
1693 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1694 } else if (Kind == OMPD_barrier) {
1695 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1696 } else {
1697 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1698 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001699 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
1700 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001701 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1702 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001703 if (auto *OMPRegionInfo =
1704 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00001705 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001706 auto *Result = CGF.EmitRuntimeCall(
1707 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001708 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001709 // if (__kmpc_cancel_barrier()) {
1710 // exit from construct;
1711 // }
1712 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
1713 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
1714 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
1715 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
1716 CGF.EmitBlock(ExitBB);
1717 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00001718 auto CancelDestination =
1719 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001720 CGF.EmitBranchThroughCleanup(CancelDestination);
1721 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
1722 }
1723 return;
1724 }
1725 }
1726 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001727}
1728
Alexander Musmanc6388682014-12-15 07:07:06 +00001729/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1730/// the enum sched_type in kmp.h).
1731enum OpenMPSchedType {
1732 /// \brief Lower bound for default (unordered) versions.
1733 OMP_sch_lower = 32,
1734 OMP_sch_static_chunked = 33,
1735 OMP_sch_static = 34,
1736 OMP_sch_dynamic_chunked = 35,
1737 OMP_sch_guided_chunked = 36,
1738 OMP_sch_runtime = 37,
1739 OMP_sch_auto = 38,
1740 /// \brief Lower bound for 'ordered' versions.
1741 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001742 OMP_ord_static_chunked = 65,
1743 OMP_ord_static = 66,
1744 OMP_ord_dynamic_chunked = 67,
1745 OMP_ord_guided_chunked = 68,
1746 OMP_ord_runtime = 69,
1747 OMP_ord_auto = 70,
1748 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001749};
1750
1751/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1752static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001753 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001754 switch (ScheduleKind) {
1755 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001756 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1757 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001758 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001759 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001760 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001761 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001762 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001763 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1764 case OMPC_SCHEDULE_auto:
1765 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001766 case OMPC_SCHEDULE_unknown:
1767 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001768 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001769 }
1770 llvm_unreachable("Unexpected runtime schedule");
1771}
1772
1773bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1774 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001775 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001776 return Schedule == OMP_sch_static;
1777}
1778
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001779bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001780 auto Schedule =
1781 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001782 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1783 return Schedule != OMP_sch_static;
1784}
1785
John McCall7f416cc2015-09-08 08:05:57 +00001786void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
1787 SourceLocation Loc,
1788 OpenMPScheduleClauseKind ScheduleKind,
1789 unsigned IVSize, bool IVSigned,
1790 bool Ordered, llvm::Value *UB,
1791 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001792 if (!CGF.HaveInsertPoint())
1793 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001794 OpenMPSchedType Schedule =
1795 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00001796 assert(Ordered ||
1797 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1798 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
1799 // Call __kmpc_dispatch_init(
1800 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1801 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1802 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001803
John McCall7f416cc2015-09-08 08:05:57 +00001804 // If the Chunk was not specified in the clause - use default value 1.
1805 if (Chunk == nullptr)
1806 Chunk = CGF.Builder.getIntN(IVSize, 1);
1807 llvm::Value *Args[] = {
1808 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1809 getThreadID(CGF, Loc),
1810 CGF.Builder.getInt32(Schedule), // Schedule type
1811 CGF.Builder.getIntN(IVSize, 0), // Lower
1812 UB, // Upper
1813 CGF.Builder.getIntN(IVSize, 1), // Stride
1814 Chunk // Chunk
1815 };
1816 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1817}
1818
1819void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
1820 SourceLocation Loc,
1821 OpenMPScheduleClauseKind ScheduleKind,
1822 unsigned IVSize, bool IVSigned,
1823 bool Ordered, Address IL, Address LB,
1824 Address UB, Address ST,
1825 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001826 if (!CGF.HaveInsertPoint())
1827 return;
John McCall7f416cc2015-09-08 08:05:57 +00001828 OpenMPSchedType Schedule =
1829 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1830 assert(!Ordered);
1831 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
1832 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked);
1833
1834 // Call __kmpc_for_static_init(
1835 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1836 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1837 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1838 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1839 if (Chunk == nullptr) {
1840 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
1841 "expected static non-chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001842 // If the Chunk was not specified in the clause - use default value 1.
Alexander Musman92bdaab2015-03-12 13:37:50 +00001843 Chunk = CGF.Builder.getIntN(IVSize, 1);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001844 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001845 assert((Schedule == OMP_sch_static_chunked ||
1846 Schedule == OMP_ord_static_chunked) &&
1847 "expected static chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001848 }
John McCall7f416cc2015-09-08 08:05:57 +00001849 llvm::Value *Args[] = {
1850 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1851 getThreadID(CGF, Loc),
1852 CGF.Builder.getInt32(Schedule), // Schedule type
1853 IL.getPointer(), // &isLastIter
1854 LB.getPointer(), // &LB
1855 UB.getPointer(), // &UB
1856 ST.getPointer(), // &Stride
1857 CGF.Builder.getIntN(IVSize, 1), // Incr
1858 Chunk // Chunk
1859 };
1860 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001861}
1862
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001863void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1864 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001865 if (!CGF.HaveInsertPoint())
1866 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00001867 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001868 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1869 getThreadID(CGF, Loc)};
1870 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1871 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001872}
1873
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001874void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1875 SourceLocation Loc,
1876 unsigned IVSize,
1877 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001878 if (!CGF.HaveInsertPoint())
1879 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001880 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1881 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1882 getThreadID(CGF, Loc)};
1883 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1884}
1885
Alexander Musman92bdaab2015-03-12 13:37:50 +00001886llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1887 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00001888 bool IVSigned, Address IL,
1889 Address LB, Address UB,
1890 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001891 // Call __kmpc_dispatch_next(
1892 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1893 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1894 // kmp_int[32|64] *p_stride);
1895 llvm::Value *Args[] = {
1896 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001897 IL.getPointer(), // &isLastIter
1898 LB.getPointer(), // &Lower
1899 UB.getPointer(), // &Upper
1900 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00001901 };
1902 llvm::Value *Call =
1903 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1904 return CGF.EmitScalarConversion(
1905 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001906 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001907}
1908
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001909void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1910 llvm::Value *NumThreads,
1911 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001912 if (!CGF.HaveInsertPoint())
1913 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00001914 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1915 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001916 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001917 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001918 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1919 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001920}
1921
Alexey Bataev7f210c62015-06-18 13:40:03 +00001922void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
1923 OpenMPProcBindClauseKind ProcBind,
1924 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001925 if (!CGF.HaveInsertPoint())
1926 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00001927 // Constants for proc bind value accepted by the runtime.
1928 enum ProcBindTy {
1929 ProcBindFalse = 0,
1930 ProcBindTrue,
1931 ProcBindMaster,
1932 ProcBindClose,
1933 ProcBindSpread,
1934 ProcBindIntel,
1935 ProcBindDefault
1936 } RuntimeProcBind;
1937 switch (ProcBind) {
1938 case OMPC_PROC_BIND_master:
1939 RuntimeProcBind = ProcBindMaster;
1940 break;
1941 case OMPC_PROC_BIND_close:
1942 RuntimeProcBind = ProcBindClose;
1943 break;
1944 case OMPC_PROC_BIND_spread:
1945 RuntimeProcBind = ProcBindSpread;
1946 break;
1947 case OMPC_PROC_BIND_unknown:
1948 llvm_unreachable("Unsupported proc_bind value.");
1949 }
1950 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
1951 llvm::Value *Args[] = {
1952 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1953 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
1954 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
1955}
1956
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001957void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1958 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001959 if (!CGF.HaveInsertPoint())
1960 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001961 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001962 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1963 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001964}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001965
Alexey Bataev62b63b12015-03-10 07:28:44 +00001966namespace {
1967/// \brief Indexes of fields for type kmp_task_t.
1968enum KmpTaskTFields {
1969 /// \brief List of shared variables.
1970 KmpTaskTShareds,
1971 /// \brief Task routine.
1972 KmpTaskTRoutine,
1973 /// \brief Partition id for the untied tasks.
1974 KmpTaskTPartId,
1975 /// \brief Function with call of destructors for private variables.
1976 KmpTaskTDestructors,
1977};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001978} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00001979
Samuel Antaoee8fb302016-01-06 13:42:12 +00001980bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
1981 // FIXME: Add other entries type when they become supported.
1982 return OffloadEntriesTargetRegion.empty();
1983}
1984
1985/// \brief Initialize target region entry.
1986void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
1987 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
1988 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00001989 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00001990 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
1991 "only required for the device "
1992 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00001993 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00001994 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
1995 ++OffloadingEntriesNum;
1996}
1997
1998void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
1999 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2000 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002001 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002002 // If we are emitting code for a target, the entry is already initialized,
2003 // only has to be registered.
2004 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002005 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002006 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002007 auto &Entry =
2008 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002009 assert(Entry.isValid() && "Entry not initialized!");
2010 Entry.setAddress(Addr);
2011 Entry.setID(ID);
2012 return;
2013 } else {
2014 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002015 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002016 }
2017}
2018
2019bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002020 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2021 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002022 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2023 if (PerDevice == OffloadEntriesTargetRegion.end())
2024 return false;
2025 auto PerFile = PerDevice->second.find(FileID);
2026 if (PerFile == PerDevice->second.end())
2027 return false;
2028 auto PerParentName = PerFile->second.find(ParentName);
2029 if (PerParentName == PerFile->second.end())
2030 return false;
2031 auto PerLine = PerParentName->second.find(LineNum);
2032 if (PerLine == PerParentName->second.end())
2033 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002034 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002035 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002036 return false;
2037 return true;
2038}
2039
2040void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2041 const OffloadTargetRegionEntryInfoActTy &Action) {
2042 // Scan all target region entries and perform the provided action.
2043 for (auto &D : OffloadEntriesTargetRegion)
2044 for (auto &F : D.second)
2045 for (auto &P : F.second)
2046 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002047 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002048}
2049
2050/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2051/// \a Codegen. This is used to emit the two functions that register and
2052/// unregister the descriptor of the current compilation unit.
2053static llvm::Function *
2054createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2055 const RegionCodeGenTy &Codegen) {
2056 auto &C = CGM.getContext();
2057 FunctionArgList Args;
2058 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2059 /*Id=*/nullptr, C.VoidPtrTy);
2060 Args.push_back(&DummyPtr);
2061
2062 CodeGenFunction CGF(CGM);
2063 GlobalDecl();
2064 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2065 C.VoidTy, Args, FunctionType::ExtInfo(),
2066 /*isVariadic=*/false);
2067 auto FTy = CGM.getTypes().GetFunctionType(FI);
2068 auto *Fn =
2069 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2070 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2071 Codegen(CGF);
2072 CGF.FinishFunction();
2073 return Fn;
2074}
2075
2076llvm::Function *
2077CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2078
2079 // If we don't have entries or if we are emitting code for the device, we
2080 // don't need to do anything.
2081 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2082 return nullptr;
2083
2084 auto &M = CGM.getModule();
2085 auto &C = CGM.getContext();
2086
2087 // Get list of devices we care about
2088 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2089
2090 // We should be creating an offloading descriptor only if there are devices
2091 // specified.
2092 assert(!Devices.empty() && "No OpenMP offloading devices??");
2093
2094 // Create the external variables that will point to the begin and end of the
2095 // host entries section. These will be defined by the linker.
2096 auto *OffloadEntryTy =
2097 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2098 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2099 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002100 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002101 ".omp_offloading.entries_begin");
2102 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2103 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002104 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002105 ".omp_offloading.entries_end");
2106
2107 // Create all device images
2108 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2109 auto *DeviceImageTy = cast<llvm::StructType>(
2110 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2111
2112 for (unsigned i = 0; i < Devices.size(); ++i) {
2113 StringRef T = Devices[i].getTriple();
2114 auto *ImgBegin = new llvm::GlobalVariable(
2115 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002116 /*Initializer=*/nullptr,
2117 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002118 auto *ImgEnd = new llvm::GlobalVariable(
2119 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002120 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002121
2122 llvm::Constant *Dev =
2123 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2124 HostEntriesBegin, HostEntriesEnd, nullptr);
2125 DeviceImagesEntires.push_back(Dev);
2126 }
2127
2128 // Create device images global array.
2129 llvm::ArrayType *DeviceImagesInitTy =
2130 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2131 llvm::Constant *DeviceImagesInit =
2132 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2133
2134 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2135 M, DeviceImagesInitTy, /*isConstant=*/true,
2136 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2137 ".omp_offloading.device_images");
2138 DeviceImages->setUnnamedAddr(true);
2139
2140 // This is a Zero array to be used in the creation of the constant expressions
2141 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2142 llvm::Constant::getNullValue(CGM.Int32Ty)};
2143
2144 // Create the target region descriptor.
2145 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2146 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2147 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2148 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2149 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2150 Index),
2151 HostEntriesBegin, HostEntriesEnd, nullptr);
2152
2153 auto *Desc = new llvm::GlobalVariable(
2154 M, BinaryDescriptorTy, /*isConstant=*/true,
2155 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2156 ".omp_offloading.descriptor");
2157
2158 // Emit code to register or unregister the descriptor at execution
2159 // startup or closing, respectively.
2160
2161 // Create a variable to drive the registration and unregistration of the
2162 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2163 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2164 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2165 IdentInfo, C.CharTy);
2166
2167 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2168 CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2169 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2170 Desc);
2171 });
2172 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2173 CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2174 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2175 Desc);
2176 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2177 });
2178 return RegFn;
2179}
2180
Samuel Antao2de62b02016-02-13 23:35:10 +00002181void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2182 llvm::Constant *Addr, uint64_t Size) {
2183 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002184 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2185 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2186 llvm::LLVMContext &C = CGM.getModule().getContext();
2187 llvm::Module &M = CGM.getModule();
2188
2189 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002190 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002191
2192 // Create constant string with the name.
2193 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2194
2195 llvm::GlobalVariable *Str =
2196 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2197 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2198 ".omp_offloading.entry_name");
2199 Str->setUnnamedAddr(true);
2200 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2201
2202 // Create the entry struct.
2203 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2204 TgtOffloadEntryType, AddrPtr, StrPtr,
2205 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2206 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2207 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2208 EntryInit, ".omp_offloading.entry");
2209
2210 // The entry has to be created in the section the linker expects it to be.
2211 Entry->setSection(".omp_offloading.entries");
2212 // We can't have any padding between symbols, so we need to have 1-byte
2213 // alignment.
2214 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002215}
2216
2217void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2218 // Emit the offloading entries and metadata so that the device codegen side
2219 // can
2220 // easily figure out what to emit. The produced metadata looks like this:
2221 //
2222 // !omp_offload.info = !{!1, ...}
2223 //
2224 // Right now we only generate metadata for function that contain target
2225 // regions.
2226
2227 // If we do not have entries, we dont need to do anything.
2228 if (OffloadEntriesInfoManager.empty())
2229 return;
2230
2231 llvm::Module &M = CGM.getModule();
2232 llvm::LLVMContext &C = M.getContext();
2233 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2234 OrderedEntries(OffloadEntriesInfoManager.size());
2235
2236 // Create the offloading info metadata node.
2237 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2238
2239 // Auxiliar methods to create metadata values and strings.
2240 auto getMDInt = [&](unsigned v) {
2241 return llvm::ConstantAsMetadata::get(
2242 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2243 };
2244
2245 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2246
2247 // Create function that emits metadata for each target region entry;
2248 auto &&TargetRegionMetadataEmitter = [&](
2249 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002250 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2251 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2252 // Generate metadata for target regions. Each entry of this metadata
2253 // contains:
2254 // - Entry 0 -> Kind of this type of metadata (0).
2255 // - Entry 1 -> Device ID of the file where the entry was identified.
2256 // - Entry 2 -> File ID of the file where the entry was identified.
2257 // - Entry 3 -> Mangled name of the function where the entry was identified.
2258 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002259 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002260 // The first element of the metadata node is the kind.
2261 Ops.push_back(getMDInt(E.getKind()));
2262 Ops.push_back(getMDInt(DeviceID));
2263 Ops.push_back(getMDInt(FileID));
2264 Ops.push_back(getMDString(ParentName));
2265 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002266 Ops.push_back(getMDInt(E.getOrder()));
2267
2268 // Save this entry in the right position of the ordered entries array.
2269 OrderedEntries[E.getOrder()] = &E;
2270
2271 // Add metadata to the named metadata node.
2272 MD->addOperand(llvm::MDNode::get(C, Ops));
2273 };
2274
2275 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2276 TargetRegionMetadataEmitter);
2277
2278 for (auto *E : OrderedEntries) {
2279 assert(E && "All ordered entries must exist!");
2280 if (auto *CE =
2281 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2282 E)) {
2283 assert(CE->getID() && CE->getAddress() &&
2284 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002285 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002286 } else
2287 llvm_unreachable("Unsupported entry kind.");
2288 }
2289}
2290
2291/// \brief Loads all the offload entries information from the host IR
2292/// metadata.
2293void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2294 // If we are in target mode, load the metadata from the host IR. This code has
2295 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2296
2297 if (!CGM.getLangOpts().OpenMPIsDevice)
2298 return;
2299
2300 if (CGM.getLangOpts().OMPHostIRFile.empty())
2301 return;
2302
2303 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2304 if (Buf.getError())
2305 return;
2306
2307 llvm::LLVMContext C;
2308 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2309
2310 if (ME.getError())
2311 return;
2312
2313 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2314 if (!MD)
2315 return;
2316
2317 for (auto I : MD->operands()) {
2318 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2319
2320 auto getMDInt = [&](unsigned Idx) {
2321 llvm::ConstantAsMetadata *V =
2322 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2323 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2324 };
2325
2326 auto getMDString = [&](unsigned Idx) {
2327 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2328 return V->getString();
2329 };
2330
2331 switch (getMDInt(0)) {
2332 default:
2333 llvm_unreachable("Unexpected metadata!");
2334 break;
2335 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2336 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2337 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2338 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2339 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002340 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002341 break;
2342 }
2343 }
2344}
2345
Alexey Bataev62b63b12015-03-10 07:28:44 +00002346void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2347 if (!KmpRoutineEntryPtrTy) {
2348 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2349 auto &C = CGM.getContext();
2350 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2351 FunctionProtoType::ExtProtoInfo EPI;
2352 KmpRoutineEntryPtrQTy = C.getPointerType(
2353 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2354 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2355 }
2356}
2357
Alexey Bataevc71a4092015-09-11 10:29:41 +00002358static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2359 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002360 auto *Field = FieldDecl::Create(
2361 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2362 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2363 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2364 Field->setAccess(AS_public);
2365 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002366 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002367}
2368
Samuel Antaoee8fb302016-01-06 13:42:12 +00002369QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2370
2371 // Make sure the type of the entry is already created. This is the type we
2372 // have to create:
2373 // struct __tgt_offload_entry{
2374 // void *addr; // Pointer to the offload entry info.
2375 // // (function or global)
2376 // char *name; // Name of the function or global.
2377 // size_t size; // Size of the entry info (0 if it a function).
2378 // };
2379 if (TgtOffloadEntryQTy.isNull()) {
2380 ASTContext &C = CGM.getContext();
2381 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2382 RD->startDefinition();
2383 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2384 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2385 addFieldToRecordDecl(C, RD, C.getSizeType());
2386 RD->completeDefinition();
2387 TgtOffloadEntryQTy = C.getRecordType(RD);
2388 }
2389 return TgtOffloadEntryQTy;
2390}
2391
2392QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2393 // These are the types we need to build:
2394 // struct __tgt_device_image{
2395 // void *ImageStart; // Pointer to the target code start.
2396 // void *ImageEnd; // Pointer to the target code end.
2397 // // We also add the host entries to the device image, as it may be useful
2398 // // for the target runtime to have access to that information.
2399 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2400 // // the entries.
2401 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2402 // // entries (non inclusive).
2403 // };
2404 if (TgtDeviceImageQTy.isNull()) {
2405 ASTContext &C = CGM.getContext();
2406 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2407 RD->startDefinition();
2408 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2409 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2410 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2411 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2412 RD->completeDefinition();
2413 TgtDeviceImageQTy = C.getRecordType(RD);
2414 }
2415 return TgtDeviceImageQTy;
2416}
2417
2418QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2419 // struct __tgt_bin_desc{
2420 // int32_t NumDevices; // Number of devices supported.
2421 // __tgt_device_image *DeviceImages; // Arrays of device images
2422 // // (one per device).
2423 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2424 // // entries.
2425 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2426 // // entries (non inclusive).
2427 // };
2428 if (TgtBinaryDescriptorQTy.isNull()) {
2429 ASTContext &C = CGM.getContext();
2430 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2431 RD->startDefinition();
2432 addFieldToRecordDecl(
2433 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2434 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2435 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2436 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2437 RD->completeDefinition();
2438 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2439 }
2440 return TgtBinaryDescriptorQTy;
2441}
2442
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002443namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002444struct PrivateHelpersTy {
2445 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2446 const VarDecl *PrivateElemInit)
2447 : Original(Original), PrivateCopy(PrivateCopy),
2448 PrivateElemInit(PrivateElemInit) {}
2449 const VarDecl *Original;
2450 const VarDecl *PrivateCopy;
2451 const VarDecl *PrivateElemInit;
2452};
2453typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002454} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002455
Alexey Bataev9e034042015-05-05 04:05:12 +00002456static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002457createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002458 if (!Privates.empty()) {
2459 auto &C = CGM.getContext();
2460 // Build struct .kmp_privates_t. {
2461 // /* private vars */
2462 // };
2463 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2464 RD->startDefinition();
2465 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002466 auto *VD = Pair.second.Original;
2467 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002468 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002469 auto *FD = addFieldToRecordDecl(C, RD, Type);
2470 if (VD->hasAttrs()) {
2471 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2472 E(VD->getAttrs().end());
2473 I != E; ++I)
2474 FD->addAttr(*I);
2475 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002476 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002477 RD->completeDefinition();
2478 return RD;
2479 }
2480 return nullptr;
2481}
2482
Alexey Bataev9e034042015-05-05 04:05:12 +00002483static RecordDecl *
2484createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002485 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002486 auto &C = CGM.getContext();
2487 // Build struct kmp_task_t {
2488 // void * shareds;
2489 // kmp_routine_entry_t routine;
2490 // kmp_int32 part_id;
2491 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002492 // };
2493 auto *RD = C.buildImplicitRecord("kmp_task_t");
2494 RD->startDefinition();
2495 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2496 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2497 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2498 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002499 RD->completeDefinition();
2500 return RD;
2501}
2502
2503static RecordDecl *
2504createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002505 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002506 auto &C = CGM.getContext();
2507 // Build struct kmp_task_t_with_privates {
2508 // kmp_task_t task_data;
2509 // .kmp_privates_t. privates;
2510 // };
2511 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2512 RD->startDefinition();
2513 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002514 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2515 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2516 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002517 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002518 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002519}
2520
2521/// \brief Emit a proxy function which accepts kmp_task_t as the second
2522/// argument.
2523/// \code
2524/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002525/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2526/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002527/// return 0;
2528/// }
2529/// \endcode
2530static llvm::Value *
2531emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002532 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2533 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002534 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2535 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002536 auto &C = CGM.getContext();
2537 FunctionArgList Args;
2538 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2539 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002540 /*Id=*/nullptr,
2541 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002542 Args.push_back(&GtidArg);
2543 Args.push_back(&TaskTypeArg);
2544 FunctionType::ExtInfo Info;
2545 auto &TaskEntryFnInfo =
2546 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2547 /*isVariadic=*/false);
2548 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2549 auto *TaskEntry =
2550 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2551 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002552 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002553 CodeGenFunction CGF(CGM);
2554 CGF.disableDebugInfo();
2555 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2556
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002557 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2558 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002559 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002560 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002561 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2562 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2563 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002564 auto *KmpTaskTWithPrivatesQTyRD =
2565 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002566 LValue Base =
2567 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002568 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2569 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2570 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
2571 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
2572
2573 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
2574 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002575 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002576 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002577 CGF.ConvertTypeForMem(SharedsPtrTy));
2578
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002579 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
2580 llvm::Value *PrivatesParam;
2581 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
2582 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
2583 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002584 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002585 } else {
2586 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2587 }
2588
2589 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
2590 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002591 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2592 CGF.EmitStoreThroughLValue(
2593 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002594 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002595 CGF.FinishFunction();
2596 return TaskEntry;
2597}
2598
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002599static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2600 SourceLocation Loc,
2601 QualType KmpInt32Ty,
2602 QualType KmpTaskTWithPrivatesPtrQTy,
2603 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002604 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002605 FunctionArgList Args;
2606 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2607 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002608 /*Id=*/nullptr,
2609 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002610 Args.push_back(&GtidArg);
2611 Args.push_back(&TaskTypeArg);
2612 FunctionType::ExtInfo Info;
2613 auto &DestructorFnInfo =
2614 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2615 /*isVariadic=*/false);
2616 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2617 auto *DestructorFn =
2618 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2619 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002620 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
2621 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002622 CodeGenFunction CGF(CGM);
2623 CGF.disableDebugInfo();
2624 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
2625 Args);
2626
Alexey Bataev31300ed2016-02-04 11:27:03 +00002627 LValue Base = CGF.EmitLoadOfPointerLValue(
2628 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2629 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002630 auto *KmpTaskTWithPrivatesQTyRD =
2631 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2632 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002633 Base = CGF.EmitLValueForField(Base, *FI);
2634 for (auto *Field :
2635 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
2636 if (auto DtorKind = Field->getType().isDestructedType()) {
2637 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
2638 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
2639 }
2640 }
2641 CGF.FinishFunction();
2642 return DestructorFn;
2643}
2644
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002645/// \brief Emit a privates mapping function for correct handling of private and
2646/// firstprivate variables.
2647/// \code
2648/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
2649/// **noalias priv1,..., <tyn> **noalias privn) {
2650/// *priv1 = &.privates.priv1;
2651/// ...;
2652/// *privn = &.privates.privn;
2653/// }
2654/// \endcode
2655static llvm::Value *
2656emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00002657 ArrayRef<const Expr *> PrivateVars,
2658 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002659 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002660 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002661 auto &C = CGM.getContext();
2662 FunctionArgList Args;
2663 ImplicitParamDecl TaskPrivatesArg(
2664 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2665 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2666 Args.push_back(&TaskPrivatesArg);
2667 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2668 unsigned Counter = 1;
2669 for (auto *E: PrivateVars) {
2670 Args.push_back(ImplicitParamDecl::Create(
2671 C, /*DC=*/nullptr, Loc,
2672 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2673 .withConst()
2674 .withRestrict()));
2675 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2676 PrivateVarsPos[VD] = Counter;
2677 ++Counter;
2678 }
2679 for (auto *E : FirstprivateVars) {
2680 Args.push_back(ImplicitParamDecl::Create(
2681 C, /*DC=*/nullptr, Loc,
2682 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2683 .withConst()
2684 .withRestrict()));
2685 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2686 PrivateVarsPos[VD] = Counter;
2687 ++Counter;
2688 }
2689 FunctionType::ExtInfo Info;
2690 auto &TaskPrivatesMapFnInfo =
2691 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2692 /*isVariadic=*/false);
2693 auto *TaskPrivatesMapTy =
2694 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2695 auto *TaskPrivatesMap = llvm::Function::Create(
2696 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2697 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002698 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
2699 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00002700 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002701 CodeGenFunction CGF(CGM);
2702 CGF.disableDebugInfo();
2703 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2704 TaskPrivatesMapFnInfo, Args);
2705
2706 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00002707 LValue Base = CGF.EmitLoadOfPointerLValue(
2708 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
2709 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002710 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2711 Counter = 0;
2712 for (auto *Field : PrivatesQTyRD->fields()) {
2713 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2714 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00002715 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00002716 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
2717 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002718 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002719 ++Counter;
2720 }
2721 CGF.FinishFunction();
2722 return TaskPrivatesMap;
2723}
2724
Alexey Bataev9e034042015-05-05 04:05:12 +00002725static int array_pod_sort_comparator(const PrivateDataTy *P1,
2726 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002727 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2728}
2729
2730void CGOpenMPRuntime::emitTaskCall(
2731 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2732 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00002733 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002734 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2735 ArrayRef<const Expr *> PrivateCopies,
2736 ArrayRef<const Expr *> FirstprivateVars,
2737 ArrayRef<const Expr *> FirstprivateCopies,
2738 ArrayRef<const Expr *> FirstprivateInits,
2739 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002740 if (!CGF.HaveInsertPoint())
2741 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002742 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002743 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002744 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002745 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002746 for (auto *E : PrivateVars) {
2747 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2748 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00002749 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00002750 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2751 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002752 ++I;
2753 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002754 I = FirstprivateCopies.begin();
2755 auto IElemInitRef = FirstprivateInits.begin();
2756 for (auto *E : FirstprivateVars) {
2757 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2758 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00002759 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00002760 PrivateHelpersTy(
2761 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2762 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00002763 ++I;
2764 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00002765 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002766 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2767 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002768 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2769 // Build type kmp_routine_entry_t (if not built yet).
2770 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002771 // Build type kmp_task_t (if not built yet).
2772 if (KmpTaskTQTy.isNull()) {
2773 KmpTaskTQTy = C.getRecordType(
2774 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2775 }
2776 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002777 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002778 auto *KmpTaskTWithPrivatesQTyRD =
2779 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2780 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2781 QualType KmpTaskTWithPrivatesPtrQTy =
2782 C.getPointerType(KmpTaskTWithPrivatesQTy);
2783 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2784 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00002785 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002786 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2787
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002788 // Emit initial values for private copies (if any).
2789 llvm::Value *TaskPrivatesMap = nullptr;
2790 auto *TaskPrivatesMapTy =
2791 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2792 3)
2793 ->getType();
2794 if (!Privates.empty()) {
2795 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2796 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2797 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2798 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2799 TaskPrivatesMap, TaskPrivatesMapTy);
2800 } else {
2801 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2802 cast<llvm::PointerType>(TaskPrivatesMapTy));
2803 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002804 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2805 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002806 auto *TaskEntry = emitProxyTaskFunction(
2807 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002808 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002809
2810 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2811 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2812 // kmp_routine_entry_t *task_entry);
2813 // Task flags. Format is taken from
2814 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2815 // description of kmp_tasking_flags struct.
2816 const unsigned TiedFlag = 0x1;
2817 const unsigned FinalFlag = 0x2;
2818 unsigned Flags = Tied ? TiedFlag : 0;
2819 auto *TaskFlags =
2820 Final.getPointer()
2821 ? CGF.Builder.CreateSelect(Final.getPointer(),
2822 CGF.Builder.getInt32(FinalFlag),
2823 CGF.Builder.getInt32(/*C=*/0))
2824 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2825 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00002826 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002827 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
2828 getThreadID(CGF, Loc), TaskFlags,
2829 KmpTaskTWithPrivatesTySize, SharedsSize,
2830 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2831 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002832 auto *NewTask = CGF.EmitRuntimeCall(
2833 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002834 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2835 NewTask, KmpTaskTWithPrivatesPtrTy);
2836 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2837 KmpTaskTWithPrivatesQTy);
2838 LValue TDBase =
2839 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002840 // Fill the data in the resulting kmp_task_t record.
2841 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00002842 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002843 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002844 KmpTaskSharedsPtr =
2845 Address(CGF.EmitLoadOfScalar(
2846 CGF.EmitLValueForField(
2847 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
2848 KmpTaskTShareds)),
2849 Loc),
2850 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002851 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002852 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002853 // Emit initial values for private copies (if any).
2854 bool NeedsCleanup = false;
2855 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002856 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2857 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002858 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002859 LValue SharedsBase;
2860 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002861 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002862 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2863 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2864 SharedsTy);
2865 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002866 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2867 cast<CapturedStmt>(*D.getAssociatedStmt()));
2868 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002869 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002870 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002871 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002872 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002873 if (auto *Elem = Pair.second.PrivateElemInit) {
2874 auto *OriginalVD = Pair.second.Original;
2875 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2876 auto SharedRefLValue =
2877 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002878 SharedRefLValue = CGF.MakeAddrLValue(
2879 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
2880 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002881 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002882 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002883 // Initialize firstprivate array.
2884 if (!isa<CXXConstructExpr>(Init) ||
2885 CGF.isTrivialInitializer(Init)) {
2886 // Perform simple memcpy.
2887 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002888 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002889 } else {
2890 // Initialize firstprivate array using element-by-element
2891 // intialization.
2892 CGF.EmitOMPAggregateAssign(
2893 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002894 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00002895 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002896 // Clean up any temporaries needed by the initialization.
2897 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002898 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002899 return SrcElement;
2900 });
2901 (void)InitScope.Privatize();
2902 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002903 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2904 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002905 CGF.EmitAnyExprToMem(Init, DestElement,
2906 Init->getType().getQualifiers(),
2907 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002908 });
2909 }
2910 } else {
2911 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002912 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002913 return SharedRefLValue.getAddress();
2914 });
2915 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002916 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002917 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2918 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002919 }
2920 } else {
2921 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2922 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002923 }
2924 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002925 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002926 }
2927 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002928 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002929 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002930 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2931 KmpTaskTWithPrivatesPtrQTy,
2932 KmpTaskTWithPrivatesQTy)
2933 : llvm::ConstantPointerNull::get(
2934 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2935 LValue Destructor = CGF.EmitLValueForField(
2936 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2937 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2938 DestructorFn, KmpRoutineEntryPtrTy),
2939 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002940
2941 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00002942 Address DependenciesArray = Address::invalid();
2943 unsigned NumDependencies = Dependences.size();
2944 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002945 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00002946 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002947 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2948 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002949 QualType FlagsTy =
2950 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002951 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2952 if (KmpDependInfoTy.isNull()) {
2953 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2954 KmpDependInfoRD->startDefinition();
2955 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2956 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2957 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2958 KmpDependInfoRD->completeDefinition();
2959 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2960 } else {
2961 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2962 }
John McCall7f416cc2015-09-08 08:05:57 +00002963 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002964 // Define type kmp_depend_info[<Dependences.size()>];
2965 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00002966 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002967 ArrayType::Normal, /*IndexTypeQuals=*/0);
2968 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00002969 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2970 for (unsigned i = 0; i < NumDependencies; ++i) {
2971 const Expr *E = Dependences[i].second;
2972 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002973 llvm::Value *Size;
2974 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002975 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
2976 LValue UpAddrLVal =
2977 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
2978 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00002979 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002980 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00002981 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002982 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
2983 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002984 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00002985 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002986 auto Base = CGF.MakeAddrLValue(
2987 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002988 KmpDependInfoTy);
2989 // deps[i].base_addr = &<Dependences[i].second>;
2990 auto BaseAddrLVal = CGF.EmitLValueForField(
2991 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00002992 CGF.EmitStoreOfScalar(
2993 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
2994 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002995 // deps[i].len = sizeof(<Dependences[i].second>);
2996 auto LenLVal = CGF.EmitLValueForField(
2997 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2998 CGF.EmitStoreOfScalar(Size, LenLVal);
2999 // deps[i].flags = <Dependences[i].first>;
3000 RTLDependenceKindTy DepKind;
3001 switch (Dependences[i].first) {
3002 case OMPC_DEPEND_in:
3003 DepKind = DepIn;
3004 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003005 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003006 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003007 case OMPC_DEPEND_inout:
3008 DepKind = DepInOut;
3009 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003010 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003011 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003012 case OMPC_DEPEND_unknown:
3013 llvm_unreachable("Unknown task dependence type");
3014 }
3015 auto FlagsLVal = CGF.EmitLValueForField(
3016 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3017 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3018 FlagsLVal);
3019 }
John McCall7f416cc2015-09-08 08:05:57 +00003020 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3021 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003022 CGF.VoidPtrTy);
3023 }
3024
Alexey Bataev62b63b12015-03-10 07:28:44 +00003025 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3026 // libcall.
3027 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3028 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003029 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3030 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3031 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3032 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003033 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003034 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003035 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3036 llvm::Value *DepTaskArgs[7];
3037 if (NumDependencies) {
3038 DepTaskArgs[0] = UpLoc;
3039 DepTaskArgs[1] = ThreadID;
3040 DepTaskArgs[2] = NewTask;
3041 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3042 DepTaskArgs[4] = DependenciesArray.getPointer();
3043 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3044 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3045 }
3046 auto &&ThenCodeGen = [this, NumDependencies,
3047 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3048 // TODO: add check for untied tasks.
3049 if (NumDependencies) {
3050 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3051 DepTaskArgs);
3052 } else {
3053 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3054 TaskArgs);
3055 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003056 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003057 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3058 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00003059
3060 llvm::Value *DepWaitTaskArgs[6];
3061 if (NumDependencies) {
3062 DepWaitTaskArgs[0] = UpLoc;
3063 DepWaitTaskArgs[1] = ThreadID;
3064 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3065 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3066 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3067 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3068 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003069 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00003070 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003071 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3072 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3073 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3074 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3075 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003076 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003077 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3078 DepWaitTaskArgs);
3079 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3080 // kmp_task_t *new_task);
3081 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3082 TaskArgs);
3083 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3084 // kmp_task_t *new_task);
3085 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3086 NormalAndEHCleanup,
3087 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3088 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00003089
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003090 // Call proxy_task_entry(gtid, new_task);
3091 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3092 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3093 };
John McCall7f416cc2015-09-08 08:05:57 +00003094
Alexey Bataev1d677132015-04-22 13:57:31 +00003095 if (IfCond) {
3096 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3097 } else {
3098 CodeGenFunction::RunCleanupsScope Scope(CGF);
3099 ThenCodeGen(CGF);
3100 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003101}
3102
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003103/// \brief Emit reduction operation for each element of array (required for
3104/// array sections) LHS op = RHS.
3105/// \param Type Type of array.
3106/// \param LHSVar Variable on the left side of the reduction operation
3107/// (references element of array in original variable).
3108/// \param RHSVar Variable on the right side of the reduction operation
3109/// (references element of array in original variable).
3110/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3111/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003112static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003113 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3114 const VarDecl *RHSVar,
3115 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3116 const Expr *, const Expr *)> &RedOpGen,
3117 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3118 const Expr *UpExpr = nullptr) {
3119 // Perform element-by-element initialization.
3120 QualType ElementTy;
3121 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3122 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3123
3124 // Drill down to the base element type on both arrays.
3125 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3126 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3127
3128 auto RHSBegin = RHSAddr.getPointer();
3129 auto LHSBegin = LHSAddr.getPointer();
3130 // Cast from pointer to array type to pointer to single element.
3131 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3132 // The basic structure here is a while-do loop.
3133 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3134 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3135 auto IsEmpty =
3136 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3137 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3138
3139 // Enter the loop body, making that address the current address.
3140 auto EntryBB = CGF.Builder.GetInsertBlock();
3141 CGF.EmitBlock(BodyBB);
3142
3143 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3144
3145 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3146 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3147 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3148 Address RHSElementCurrent =
3149 Address(RHSElementPHI,
3150 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3151
3152 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3153 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3154 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3155 Address LHSElementCurrent =
3156 Address(LHSElementPHI,
3157 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3158
3159 // Emit copy.
3160 CodeGenFunction::OMPPrivateScope Scope(CGF);
3161 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3162 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3163 Scope.Privatize();
3164 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3165 Scope.ForceCleanup();
3166
3167 // Shift the address forward by one element.
3168 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3169 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3170 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3171 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3172 // Check whether we've reached the end.
3173 auto Done =
3174 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3175 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3176 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3177 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3178
3179 // Done.
3180 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3181}
3182
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003183static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3184 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003185 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003186 ArrayRef<const Expr *> LHSExprs,
3187 ArrayRef<const Expr *> RHSExprs,
3188 ArrayRef<const Expr *> ReductionOps) {
3189 auto &C = CGM.getContext();
3190
3191 // void reduction_func(void *LHSArg, void *RHSArg);
3192 FunctionArgList Args;
3193 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3194 C.VoidPtrTy);
3195 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3196 C.VoidPtrTy);
3197 Args.push_back(&LHSArg);
3198 Args.push_back(&RHSArg);
3199 FunctionType::ExtInfo EI;
3200 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3201 C.VoidTy, Args, EI, /*isVariadic=*/false);
3202 auto *Fn = llvm::Function::Create(
3203 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3204 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003205 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003206 CodeGenFunction CGF(CGM);
3207 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3208
3209 // Dst = (void*[n])(LHSArg);
3210 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003211 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3212 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3213 ArgsType), CGF.getPointerAlign());
3214 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3215 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3216 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003217
3218 // ...
3219 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3220 // ...
3221 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003222 auto IPriv = Privates.begin();
3223 unsigned Idx = 0;
3224 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003225 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3226 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003227 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003228 });
3229 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3230 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003231 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003232 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003233 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003234 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003235 // Get array size and emit VLA type.
3236 ++Idx;
3237 Address Elem =
3238 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3239 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003240 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3241 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003242 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003243 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003244 CGF.EmitVariablyModifiedType(PrivTy);
3245 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003246 }
3247 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003248 IPriv = Privates.begin();
3249 auto ILHS = LHSExprs.begin();
3250 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003251 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003252 if ((*IPriv)->getType()->isArrayType()) {
3253 // Emit reduction for array section.
3254 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3255 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3256 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3257 [=](CodeGenFunction &CGF, const Expr *,
3258 const Expr *,
3259 const Expr *) { CGF.EmitIgnoredExpr(E); });
3260 } else
3261 // Emit reduction for array subscript or single variable.
3262 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003263 ++IPriv;
3264 ++ILHS;
3265 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003266 }
3267 Scope.ForceCleanup();
3268 CGF.FinishFunction();
3269 return Fn;
3270}
3271
3272void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003273 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003274 ArrayRef<const Expr *> LHSExprs,
3275 ArrayRef<const Expr *> RHSExprs,
3276 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003277 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003278 if (!CGF.HaveInsertPoint())
3279 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003280 // Next code should be emitted for reduction:
3281 //
3282 // static kmp_critical_name lock = { 0 };
3283 //
3284 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3285 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3286 // ...
3287 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3288 // *(Type<n>-1*)rhs[<n>-1]);
3289 // }
3290 //
3291 // ...
3292 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3293 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3294 // RedList, reduce_func, &<lock>)) {
3295 // case 1:
3296 // ...
3297 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3298 // ...
3299 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3300 // break;
3301 // case 2:
3302 // ...
3303 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3304 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003305 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003306 // break;
3307 // default:;
3308 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003309 //
3310 // if SimpleReduction is true, only the next code is generated:
3311 // ...
3312 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3313 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003314
3315 auto &C = CGM.getContext();
3316
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003317 if (SimpleReduction) {
3318 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003319 auto IPriv = Privates.begin();
3320 auto ILHS = LHSExprs.begin();
3321 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003322 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003323 if ((*IPriv)->getType()->isArrayType()) {
3324 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3325 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3326 EmitOMPAggregateReduction(
3327 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3328 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3329 const Expr *) { CGF.EmitIgnoredExpr(E); });
3330 } else
3331 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003332 ++IPriv;
3333 ++ILHS;
3334 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003335 }
3336 return;
3337 }
3338
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003339 // 1. Build a list of reduction variables.
3340 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003341 auto Size = RHSExprs.size();
3342 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003343 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003344 // Reserve place for array size.
3345 ++Size;
3346 }
3347 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003348 QualType ReductionArrayTy =
3349 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3350 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003351 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003352 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003353 auto IPriv = Privates.begin();
3354 unsigned Idx = 0;
3355 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003356 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003357 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003358 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003359 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003360 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3361 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003362 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003363 // Store array size.
3364 ++Idx;
3365 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3366 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003367 llvm::Value *Size = CGF.Builder.CreateIntCast(
3368 CGF.getVLASize(
3369 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3370 .first,
3371 CGF.SizeTy, /*isSigned=*/false);
3372 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3373 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003374 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003375 }
3376
3377 // 2. Emit reduce_func().
3378 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003379 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3380 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003381
3382 // 3. Create static kmp_critical_name lock = { 0 };
3383 auto *Lock = getCriticalRegionLock(".reduction");
3384
3385 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3386 // RedList, reduce_func, &<lock>);
3387 auto *IdentTLoc = emitUpdateLocation(
3388 CGF, Loc,
3389 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
3390 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003391 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003392 auto *RL =
3393 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3394 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003395 llvm::Value *Args[] = {
3396 IdentTLoc, // ident_t *<loc>
3397 ThreadId, // i32 <gtid>
3398 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3399 ReductionArrayTySize, // size_type sizeof(RedList)
3400 RL, // void *RedList
3401 ReductionFn, // void (*) (void *, void *) <reduce_func>
3402 Lock // kmp_critical_name *&<lock>
3403 };
3404 auto Res = CGF.EmitRuntimeCall(
3405 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3406 : OMPRTL__kmpc_reduce),
3407 Args);
3408
3409 // 5. Build switch(res)
3410 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3411 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3412
3413 // 6. Build case 1:
3414 // ...
3415 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3416 // ...
3417 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3418 // break;
3419 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3420 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3421 CGF.EmitBlock(Case1BB);
3422
3423 {
3424 CodeGenFunction::RunCleanupsScope Scope(CGF);
3425 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3426 llvm::Value *EndArgs[] = {
3427 IdentTLoc, // ident_t *<loc>
3428 ThreadId, // i32 <gtid>
3429 Lock // kmp_critical_name *&<lock>
3430 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003431 CGF.EHStack
3432 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3433 NormalAndEHCleanup,
3434 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3435 : OMPRTL__kmpc_end_reduce),
3436 llvm::makeArrayRef(EndArgs));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003437 auto IPriv = Privates.begin();
3438 auto ILHS = LHSExprs.begin();
3439 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003440 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003441 if ((*IPriv)->getType()->isArrayType()) {
3442 // Emit reduction for array section.
3443 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3444 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3445 EmitOMPAggregateReduction(
3446 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3447 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3448 const Expr *) { CGF.EmitIgnoredExpr(E); });
3449 } else
3450 // Emit reduction for array subscript or single variable.
3451 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003452 ++IPriv;
3453 ++ILHS;
3454 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003455 }
3456 }
3457
3458 CGF.EmitBranch(DefaultBB);
3459
3460 // 7. Build case 2:
3461 // ...
3462 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3463 // ...
3464 // break;
3465 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3466 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3467 CGF.EmitBlock(Case2BB);
3468
3469 {
3470 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00003471 if (!WithNowait) {
3472 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3473 llvm::Value *EndArgs[] = {
3474 IdentTLoc, // ident_t *<loc>
3475 ThreadId, // i32 <gtid>
3476 Lock // kmp_critical_name *&<lock>
3477 };
3478 CGF.EHStack
3479 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3480 NormalAndEHCleanup,
3481 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3482 llvm::makeArrayRef(EndArgs));
3483 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003484 auto ILHS = LHSExprs.begin();
3485 auto IRHS = RHSExprs.begin();
3486 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003487 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003488 const Expr *XExpr = nullptr;
3489 const Expr *EExpr = nullptr;
3490 const Expr *UpExpr = nullptr;
3491 BinaryOperatorKind BO = BO_Comma;
3492 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3493 if (BO->getOpcode() == BO_Assign) {
3494 XExpr = BO->getLHS();
3495 UpExpr = BO->getRHS();
3496 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003497 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003498 // Try to emit update expression as a simple atomic.
3499 auto *RHSExpr = UpExpr;
3500 if (RHSExpr) {
3501 // Analyze RHS part of the whole expression.
3502 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3503 RHSExpr->IgnoreParenImpCasts())) {
3504 // If this is a conditional operator, analyze its condition for
3505 // min/max reduction operator.
3506 RHSExpr = ACO->getCond();
3507 }
3508 if (auto *BORHS =
3509 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3510 EExpr = BORHS->getRHS();
3511 BO = BORHS->getOpcode();
3512 }
Alexey Bataev69a47792015-05-07 03:54:03 +00003513 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003514 if (XExpr) {
3515 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3516 auto &&AtomicRedGen = [this, BO, VD, IPriv,
3517 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3518 const Expr *EExpr, const Expr *UpExpr) {
3519 LValue X = CGF.EmitLValue(XExpr);
3520 RValue E;
3521 if (EExpr)
3522 E = CGF.EmitAnyExpr(EExpr);
3523 CGF.EmitOMPAtomicSimpleUpdateExpr(
3524 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
Alexey Bataev8524d152016-01-21 12:35:58 +00003525 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003526 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev8524d152016-01-21 12:35:58 +00003527 PrivateScope.addPrivate(
3528 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3529 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3530 CGF.emitOMPSimpleStore(
3531 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3532 VD->getType().getNonReferenceType(), Loc);
3533 return LHSTemp;
3534 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003535 (void)PrivateScope.Privatize();
3536 return CGF.EmitAnyExpr(UpExpr);
3537 });
3538 };
3539 if ((*IPriv)->getType()->isArrayType()) {
3540 // Emit atomic reduction for array section.
3541 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3542 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3543 AtomicRedGen, XExpr, EExpr, UpExpr);
3544 } else
3545 // Emit atomic reduction for array subscript or single variable.
3546 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3547 } else {
3548 // Emit as a critical region.
3549 auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3550 const Expr *, const Expr *) {
3551 emitCriticalRegion(
3552 CGF, ".atomic_reduction",
3553 [E](CodeGenFunction &CGF) { CGF.EmitIgnoredExpr(E); }, Loc);
3554 };
3555 if ((*IPriv)->getType()->isArrayType()) {
3556 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3557 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3558 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3559 CritRedGen);
3560 } else
3561 CritRedGen(CGF, nullptr, nullptr, nullptr);
3562 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003563 ++ILHS;
3564 ++IRHS;
3565 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003566 }
3567 }
3568
3569 CGF.EmitBranch(DefaultBB);
3570 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3571}
3572
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003573void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
3574 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003575 if (!CGF.HaveInsertPoint())
3576 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003577 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
3578 // global_tid);
3579 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3580 // Ignore return result until untied tasks are supported.
3581 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
3582}
3583
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003584void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003585 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003586 const RegionCodeGenTy &CodeGen,
3587 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003588 if (!CGF.HaveInsertPoint())
3589 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003590 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003591 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00003592}
3593
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003594namespace {
3595enum RTCancelKind {
3596 CancelNoreq = 0,
3597 CancelParallel = 1,
3598 CancelLoop = 2,
3599 CancelSections = 3,
3600 CancelTaskgroup = 4
3601};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003602} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003603
3604static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
3605 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00003606 if (CancelRegion == OMPD_parallel)
3607 CancelKind = CancelParallel;
3608 else if (CancelRegion == OMPD_for)
3609 CancelKind = CancelLoop;
3610 else if (CancelRegion == OMPD_sections)
3611 CancelKind = CancelSections;
3612 else {
3613 assert(CancelRegion == OMPD_taskgroup);
3614 CancelKind = CancelTaskgroup;
3615 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003616 return CancelKind;
3617}
3618
3619void CGOpenMPRuntime::emitCancellationPointCall(
3620 CodeGenFunction &CGF, SourceLocation Loc,
3621 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003622 if (!CGF.HaveInsertPoint())
3623 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003624 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
3625 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003626 if (auto *OMPRegionInfo =
3627 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003628 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003629 llvm::Value *Args[] = {
3630 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3631 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003632 // Ignore return result until untied tasks are supported.
3633 auto *Result = CGF.EmitRuntimeCall(
3634 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
3635 // if (__kmpc_cancellationpoint()) {
3636 // __kmpc_cancel_barrier();
3637 // exit from construct;
3638 // }
3639 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3640 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3641 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3642 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3643 CGF.EmitBlock(ExitBB);
3644 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003645 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003646 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003647 auto CancelDest =
3648 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003649 CGF.EmitBranchThroughCleanup(CancelDest);
3650 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3651 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003652 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003653}
3654
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003655void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00003656 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003657 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003658 if (!CGF.HaveInsertPoint())
3659 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003660 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
3661 // kmp_int32 cncl_kind);
3662 if (auto *OMPRegionInfo =
3663 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003664 auto &&ThenGen = [this, Loc, CancelRegion,
3665 OMPRegionInfo](CodeGenFunction &CGF) {
3666 llvm::Value *Args[] = {
3667 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3668 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
3669 // Ignore return result until untied tasks are supported.
3670 auto *Result =
3671 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
3672 // if (__kmpc_cancel()) {
3673 // __kmpc_cancel_barrier();
3674 // exit from construct;
3675 // }
3676 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3677 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3678 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3679 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3680 CGF.EmitBlock(ExitBB);
3681 // __kmpc_cancel_barrier();
3682 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
3683 // exit from construct;
3684 auto CancelDest =
3685 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3686 CGF.EmitBranchThroughCleanup(CancelDest);
3687 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3688 };
3689 if (IfCond)
3690 emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
3691 else
3692 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003693 }
3694}
Samuel Antaobed3c462015-10-02 16:14:20 +00003695
Samuel Antaoee8fb302016-01-06 13:42:12 +00003696/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00003697/// consists of the file and device IDs as well as line number associated with
3698/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003699static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
3700 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00003701 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003702
3703 auto &SM = C.getSourceManager();
3704
3705 // The loc should be always valid and have a file ID (the user cannot use
3706 // #pragma directives in macros)
3707
3708 assert(Loc.isValid() && "Source location is expected to be always valid.");
3709 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
3710
3711 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3712 assert(PLoc.isValid() && "Source location is expected to be always valid.");
3713
3714 llvm::sys::fs::UniqueID ID;
3715 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
3716 llvm_unreachable("Source file with target region no longer exists!");
3717
3718 DeviceID = ID.getDevice();
3719 FileID = ID.getFile();
3720 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003721}
3722
3723void CGOpenMPRuntime::emitTargetOutlinedFunction(
3724 const OMPExecutableDirective &D, StringRef ParentName,
3725 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
3726 bool IsOffloadEntry) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003727 assert(!ParentName.empty() && "Invalid target region parent name!");
3728
Samuel Antaobed3c462015-10-02 16:14:20 +00003729 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
3730
Samuel Antaoee8fb302016-01-06 13:42:12 +00003731 // Emit target region as a standalone region.
3732 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
3733 CGF.EmitStmt(CS.getCapturedStmt());
3734 };
3735
Samuel Antao2de62b02016-02-13 23:35:10 +00003736 // Create a unique name for the entry function using the source location
3737 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003738 //
Samuel Antao2de62b02016-02-13 23:35:10 +00003739 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00003740 //
3741 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00003742 // mangled name of the function that encloses the target region and BB is the
3743 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003744
3745 unsigned DeviceID;
3746 unsigned FileID;
3747 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003748 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00003749 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003750 SmallString<64> EntryFnName;
3751 {
3752 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00003753 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
3754 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003755 }
3756
Samuel Antaobed3c462015-10-02 16:14:20 +00003757 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003758 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00003759 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003760
3761 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
3762
3763 // If this target outline function is not an offload entry, we don't need to
3764 // register it.
3765 if (!IsOffloadEntry)
3766 return;
3767
3768 // The target region ID is used by the runtime library to identify the current
3769 // target region, so it only has to be unique and not necessarily point to
3770 // anything. It could be the pointer to the outlined function that implements
3771 // the target region, but we aren't using that so that the compiler doesn't
3772 // need to keep that, and could therefore inline the host function if proven
3773 // worthwhile during optimization. In the other hand, if emitting code for the
3774 // device, the ID has to be the function address so that it can retrieved from
3775 // the offloading entry and launched by the runtime library. We also mark the
3776 // outlined function to have external linkage in case we are emitting code for
3777 // the device, because these functions will be entry points to the device.
3778
3779 if (CGM.getLangOpts().OpenMPIsDevice) {
3780 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
3781 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
3782 } else
3783 OutlinedFnID = new llvm::GlobalVariable(
3784 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
3785 llvm::GlobalValue::PrivateLinkage,
3786 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
3787
3788 // Register the information for the entry associated with this target region.
3789 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003790 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00003791}
3792
3793void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
3794 const OMPExecutableDirective &D,
3795 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003796 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00003797 const Expr *IfCond, const Expr *Device,
3798 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003799 if (!CGF.HaveInsertPoint())
3800 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00003801 /// \brief Values for bit flags used to specify the mapping type for
3802 /// offloading.
3803 enum OpenMPOffloadMappingFlags {
3804 /// \brief Allocate memory on the device and move data from host to device.
3805 OMP_MAP_TO = 0x01,
3806 /// \brief Allocate memory on the device and move data from device to host.
3807 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003808 /// \brief The element passed to the device is a pointer.
3809 OMP_MAP_PTR = 0x20,
3810 /// \brief Pass the element to the device by value.
3811 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00003812 };
3813
3814 enum OpenMPOffloadingReservedDeviceIDs {
3815 /// \brief Device ID if the device was not defined, runtime should get it
3816 /// from environment variables in the spec.
3817 OMP_DEVICEID_UNDEF = -1,
3818 };
3819
Samuel Antaoee8fb302016-01-06 13:42:12 +00003820 assert(OutlinedFn && "Invalid outlined function!");
3821
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003822 auto &Ctx = CGF.getContext();
3823
Samuel Antaobed3c462015-10-02 16:14:20 +00003824 // Fill up the arrays with the all the captured variables.
3825 SmallVector<llvm::Value *, 16> BasePointers;
3826 SmallVector<llvm::Value *, 16> Pointers;
3827 SmallVector<llvm::Value *, 16> Sizes;
3828 SmallVector<unsigned, 16> MapTypes;
3829
3830 bool hasVLACaptures = false;
3831
3832 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
3833 auto RI = CS.getCapturedRecordDecl()->field_begin();
3834 // auto II = CS.capture_init_begin();
3835 auto CV = CapturedVars.begin();
3836 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
3837 CE = CS.capture_end();
3838 CI != CE; ++CI, ++RI, ++CV) {
3839 StringRef Name;
3840 QualType Ty;
3841 llvm::Value *BasePointer;
3842 llvm::Value *Pointer;
3843 llvm::Value *Size;
3844 unsigned MapType;
3845
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003846 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00003847 if (CI->capturesVariableArrayType()) {
3848 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00003849 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003850 // Copy to the device as an argument. No need to retrieve it.
3851 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00003852 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00003853 } else if (CI->capturesThis()) {
3854 BasePointer = Pointer = *CV;
3855 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003856 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00003857 // Default map type.
3858 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003859 } else if (CI->capturesVariableByCopy()) {
3860 MapType = OMP_MAP_BYCOPY;
3861 if (!RI->getType()->isAnyPointerType()) {
3862 // If the field is not a pointer, we need to save the actual value and
3863 // load it as a void pointer.
3864 auto DstAddr = CGF.CreateMemTemp(
3865 Ctx.getUIntPtrType(),
3866 Twine(CI->getCapturedVar()->getName()) + ".casted");
3867 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
3868
3869 auto *SrcAddrVal = CGF.EmitScalarConversion(
3870 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
3871 Ctx.getPointerType(RI->getType()), SourceLocation());
3872 LValue SrcLV =
3873 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
3874
3875 // Store the value using the source type pointer.
3876 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
3877
3878 // Load the value using the destination type pointer.
3879 BasePointer = Pointer =
3880 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
3881 } else {
3882 MapType |= OMP_MAP_PTR;
3883 BasePointer = Pointer = *CV;
3884 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00003885 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00003886 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003887 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00003888 BasePointer = Pointer = *CV;
3889
3890 const ReferenceType *PtrTy =
3891 cast<ReferenceType>(RI->getType().getTypePtr());
3892 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003893 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003894 // The default map type for a scalar/complex type is 'to' because by
3895 // default the value doesn't have to be retrieved. For an aggregate type,
3896 // the default is 'tofrom'.
3897 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
3898 : OMP_MAP_TO;
3899 if (ElementType->isAnyPointerType())
3900 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00003901 }
3902
3903 BasePointers.push_back(BasePointer);
3904 Pointers.push_back(Pointer);
3905 Sizes.push_back(Size);
3906 MapTypes.push_back(MapType);
3907 }
3908
3909 // Keep track on whether the host function has to be executed.
3910 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003911 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00003912 auto OffloadError = CGF.MakeAddrLValue(
3913 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
3914 OffloadErrorQType);
3915 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
3916 OffloadError);
3917
3918 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003919 auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003920 hasVLACaptures, Device, OutlinedFnID, OffloadError,
Samuel Antaobed3c462015-10-02 16:14:20 +00003921 OffloadErrorQType](CodeGenFunction &CGF) {
3922 unsigned PointerNumVal = BasePointers.size();
3923 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
3924 llvm::Value *BasePointersArray;
3925 llvm::Value *PointersArray;
3926 llvm::Value *SizesArray;
3927 llvm::Value *MapTypesArray;
3928
3929 if (PointerNumVal) {
3930 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003931 QualType PointerArrayType = Ctx.getConstantArrayType(
3932 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00003933 /*IndexTypeQuals=*/0);
3934
3935 BasePointersArray =
3936 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
3937 PointersArray =
3938 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
3939
3940 // If we don't have any VLA types, we can use a constant array for the map
3941 // sizes, otherwise we need to fill up the arrays as we do for the
3942 // pointers.
3943 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003944 QualType SizeArrayType = Ctx.getConstantArrayType(
3945 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00003946 /*IndexTypeQuals=*/0);
3947 SizesArray =
3948 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
3949 } else {
3950 // We expect all the sizes to be constant, so we collect them to create
3951 // a constant array.
3952 SmallVector<llvm::Constant *, 16> ConstSizes;
3953 for (auto S : Sizes)
3954 ConstSizes.push_back(cast<llvm::Constant>(S));
3955
3956 auto *SizesArrayInit = llvm::ConstantArray::get(
3957 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
3958 auto *SizesArrayGbl = new llvm::GlobalVariable(
3959 CGM.getModule(), SizesArrayInit->getType(),
3960 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
3961 SizesArrayInit, ".offload_sizes");
3962 SizesArrayGbl->setUnnamedAddr(true);
3963 SizesArray = SizesArrayGbl;
3964 }
3965
3966 // The map types are always constant so we don't need to generate code to
3967 // fill arrays. Instead, we create an array constant.
3968 llvm::Constant *MapTypesArrayInit =
3969 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
3970 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
3971 CGM.getModule(), MapTypesArrayInit->getType(),
3972 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
3973 MapTypesArrayInit, ".offload_maptypes");
3974 MapTypesArrayGbl->setUnnamedAddr(true);
3975 MapTypesArray = MapTypesArrayGbl;
3976
3977 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003978 llvm::Value *BPVal = BasePointers[i];
3979 if (BPVal->getType()->isPointerTy())
3980 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
3981 else {
3982 assert(BPVal->getType()->isIntegerTy() &&
3983 "If not a pointer, the value type must be an integer.");
3984 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
3985 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003986 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
3987 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
3988 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003989 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
3990 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00003991
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003992 llvm::Value *PVal = Pointers[i];
3993 if (PVal->getType()->isPointerTy())
3994 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
3995 else {
3996 assert(PVal->getType()->isIntegerTy() &&
3997 "If not a pointer, the value type must be an integer.");
3998 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
3999 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004000 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4001 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4002 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004003 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4004 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004005
4006 if (hasVLACaptures) {
4007 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4008 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4009 /*Idx0=*/0,
4010 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004011 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004012 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4013 Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4014 SAddr);
4015 }
4016 }
4017
4018 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4019 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4020 /*Idx0=*/0, /*Idx1=*/0);
4021 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4022 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4023 /*Idx0=*/0,
4024 /*Idx1=*/0);
4025 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4026 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4027 /*Idx0=*/0, /*Idx1=*/0);
4028 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4029 llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4030 /*Idx0=*/0,
4031 /*Idx1=*/0);
4032
4033 } else {
4034 BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4035 PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4036 SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4037 MapTypesArray =
4038 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4039 }
4040
4041 // On top of the arrays that were filled up, the target offloading call
4042 // takes as arguments the device id as well as the host pointer. The host
4043 // pointer is used by the runtime library to identify the current target
4044 // region, so it only has to be unique and not necessarily point to
4045 // anything. It could be the pointer to the outlined function that
4046 // implements the target region, but we aren't using that so that the
4047 // compiler doesn't need to keep that, and could therefore inline the host
4048 // function if proven worthwhile during optimization.
4049
Samuel Antaoee8fb302016-01-06 13:42:12 +00004050 // From this point on, we need to have an ID of the target region defined.
4051 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004052
4053 // Emit device ID if any.
4054 llvm::Value *DeviceID;
4055 if (Device)
4056 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4057 CGM.Int32Ty, /*isSigned=*/true);
4058 else
4059 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4060
4061 llvm::Value *OffloadingArgs[] = {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004062 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4063 PointersArray, SizesArray, MapTypesArray};
Samuel Antaobed3c462015-10-02 16:14:20 +00004064 auto Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4065 OffloadingArgs);
4066
4067 CGF.EmitStoreOfScalar(Return, OffloadError);
4068 };
4069
Samuel Antaoee8fb302016-01-06 13:42:12 +00004070 // Notify that the host version must be executed.
4071 auto &&ElseGen = [this, OffloadError,
4072 OffloadErrorQType](CodeGenFunction &CGF) {
4073 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4074 OffloadError);
4075 };
4076
4077 // If we have a target function ID it means that we need to support
4078 // offloading, otherwise, just execute on the host. We need to execute on host
4079 // regardless of the conditional in the if clause if, e.g., the user do not
4080 // specify target triples.
4081 if (OutlinedFnID) {
4082 if (IfCond) {
4083 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4084 } else {
4085 CodeGenFunction::RunCleanupsScope Scope(CGF);
4086 ThenGen(CGF);
4087 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004088 } else {
4089 CodeGenFunction::RunCleanupsScope Scope(CGF);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004090 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004091 }
4092
4093 // Check the error code and execute the host version if required.
4094 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4095 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4096 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4097 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4098 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4099
4100 CGF.EmitBlock(OffloadFailedBlock);
4101 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4102 CGF.EmitBranch(OffloadContBlock);
4103
4104 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004105}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004106
4107void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4108 StringRef ParentName) {
4109 if (!S)
4110 return;
4111
4112 // If we find a OMP target directive, codegen the outline function and
4113 // register the result.
4114 // FIXME: Add other directives with target when they become supported.
4115 bool isTargetDirective = isa<OMPTargetDirective>(S);
4116
4117 if (isTargetDirective) {
4118 auto *E = cast<OMPExecutableDirective>(S);
4119 unsigned DeviceID;
4120 unsigned FileID;
4121 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004122 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004123 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004124
4125 // Is this a target region that should not be emitted as an entry point? If
4126 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00004127 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4128 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004129 return;
4130
4131 llvm::Function *Fn;
4132 llvm::Constant *Addr;
4133 emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4134 /*isOffloadEntry=*/true);
4135 assert(Fn && Addr && "Target region emission failed.");
4136 return;
4137 }
4138
4139 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4140 if (!E->getAssociatedStmt())
4141 return;
4142
4143 scanForTargetRegionsFunctions(
4144 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4145 ParentName);
4146 return;
4147 }
4148
4149 // If this is a lambda function, look into its body.
4150 if (auto *L = dyn_cast<LambdaExpr>(S))
4151 S = L->getBody();
4152
4153 // Keep looking for target regions recursively.
4154 for (auto *II : S->children())
4155 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004156}
4157
4158bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4159 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4160
4161 // If emitting code for the host, we do not process FD here. Instead we do
4162 // the normal code generation.
4163 if (!CGM.getLangOpts().OpenMPIsDevice)
4164 return false;
4165
4166 // Try to detect target regions in the function.
4167 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4168
4169 // We should not emit any function othen that the ones created during the
4170 // scanning. Therefore, we signal that this function is completely dealt
4171 // with.
4172 return true;
4173}
4174
4175bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4176 if (!CGM.getLangOpts().OpenMPIsDevice)
4177 return false;
4178
4179 // Check if there are Ctors/Dtors in this declaration and look for target
4180 // regions in it. We use the complete variant to produce the kernel name
4181 // mangling.
4182 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4183 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4184 for (auto *Ctor : RD->ctors()) {
4185 StringRef ParentName =
4186 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4187 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4188 }
4189 auto *Dtor = RD->getDestructor();
4190 if (Dtor) {
4191 StringRef ParentName =
4192 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4193 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4194 }
4195 }
4196
4197 // If we are in target mode we do not emit any global (declare target is not
4198 // implemented yet). Therefore we signal that GD was processed in this case.
4199 return true;
4200}
4201
4202bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4203 auto *VD = GD.getDecl();
4204 if (isa<FunctionDecl>(VD))
4205 return emitTargetFunctions(GD);
4206
4207 return emitTargetGlobalVariable(GD);
4208}
4209
4210llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4211 // If we have offloading in the current module, we need to emit the entries
4212 // now and register the offloading descriptor.
4213 createOffloadEntriesAndInfoMetadata();
4214
4215 // Create and register the offloading binary descriptors. This is the main
4216 // entity that captures all the information about offloading in the current
4217 // compilation unit.
4218 return createOffloadingBinaryDescriptorRegistration();
4219}