blob: d2ccb33bc2acce10e8e8ad93f35c537019051b5e [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"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
195 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Alexey Bataev311a9282017-10-12 13:51:32 +0000268 /// \brief Get an LValue for the current ThreadID variable.
269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct");
273 }
274
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000275 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000276 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 llvm_unreachable("No helper name for inlined OpenMP construct");
280 }
281
Alexey Bataev48591dd2016-04-20 04:01:36 +0000282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
Alexey Bataev48591dd2016-04-20 04:01:36 +0000294 ~CGOpenMPInlinedRegionInfo() override = default;
295
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000296private:
297 /// \brief CodeGen info about outer OpenMP region.
298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000300};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000301
Samuel Antaobed3c462015-10-02 16:14:20 +0000302/// \brief API for captured statement code generation in OpenMP target
303/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 /// \brief This is unused for target regions because each starts executing
316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
319 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000320 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000326
327private:
328 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000329};
330
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000332 llvm_unreachable("No codegen for expressions");
333}
334/// \brief API for generation of expressions captured in a innermost OpenMP
335/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
346 for (auto &C : CS.captures()) {
347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
354 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
357 SourceLocation());
358 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
359 return CGF.EmitLValue(&DRE).getAddress();
360 });
361 }
362 (void)PrivScope.Privatize();
363 }
364
365 /// \brief Lookup the captured field decl for a variable.
366 const FieldDecl *lookup(const VarDecl *VD) const override {
367 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
368 return FD;
369 return nullptr;
370 }
371
372 /// \brief Emit the captured statement body.
373 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
374 llvm_unreachable("No body for expressions");
375 }
376
377 /// \brief Get a variable or parameter for storing global thread id
378 /// inside OpenMP construct.
379 const VarDecl *getThreadIDVariable() const override {
380 llvm_unreachable("No thread id for expressions");
381 }
382
383 /// \brief Get the name of the capture helper.
384 StringRef getHelperName() const override {
385 llvm_unreachable("No helper name for expressions");
386 }
387
388 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
389
390private:
391 /// Private scope to capture global variables.
392 CodeGenFunction::OMPPrivateScope PrivScope;
393};
394
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000395/// \brief RAII for emitting code of OpenMP constructs.
396class InlinedOpenMPRegionRAII {
397 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000398 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
399 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000400 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401
402public:
403 /// \brief Constructs region for combined constructs.
404 /// \param CodeGen Code generation sequence for combined directives. Includes
405 /// a list of functions used for code generation of implicitly inlined
406 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000407 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000408 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 : CGF(CGF) {
410 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000411 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
412 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
415 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000416 BlockInfo = CGF.BlockInfo;
417 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000419
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000420 ~InlinedOpenMPRegionRAII() {
421 // Restore original CapturedStmtInfo only if we're done with code emission.
422 auto *OldCSI =
423 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
424 delete CGF.CapturedStmtInfo;
425 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000426 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
427 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000428 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000429 }
430};
431
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432/// \brief Values for bit flags used in the ident_t to describe the fields.
433/// All enumeric elements are named and described in accordance with the code
434/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000435enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000436 /// \brief Use trampoline for internal microtask.
437 OMP_IDENT_IMD = 0x01,
438 /// \brief Use c-style ident structure.
439 OMP_IDENT_KMPC = 0x02,
440 /// \brief Atomic reduction option for kmpc_reduce.
441 OMP_ATOMIC_REDUCE = 0x10,
442 /// \brief Explicit 'barrier' directive.
443 OMP_IDENT_BARRIER_EXPL = 0x20,
444 /// \brief Implicit barrier in code.
445 OMP_IDENT_BARRIER_IMPL = 0x40,
446 /// \brief Implicit barrier in 'for' directive.
447 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
448 /// \brief Implicit barrier in 'sections' directive.
449 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
450 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000451 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
452 /// Call of __kmp_for_static_init for static loop.
453 OMP_IDENT_WORK_LOOP = 0x200,
454 /// Call of __kmp_for_static_init for sections.
455 OMP_IDENT_WORK_SECTIONS = 0x400,
456 /// Call of __kmp_for_static_init for distribute.
457 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
458 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000459};
460
461/// \brief Describes ident structure that describes a source location.
462/// All descriptions are taken from
463/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
464/// Original structure:
465/// typedef struct ident {
466/// kmp_int32 reserved_1; /**< might be used in Fortran;
467/// see above */
468/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
469/// KMP_IDENT_KMPC identifies this union
470/// member */
471/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
472/// see above */
473///#if USE_ITT_BUILD
474/// /* but currently used for storing
475/// region-specific ITT */
476/// /* contextual information. */
477///#endif /* USE_ITT_BUILD */
478/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
479/// C++ */
480/// char const *psource; /**< String describing the source location.
481/// The string is composed of semi-colon separated
482// fields which describe the source file,
483/// the function and a pair of line numbers that
484/// delimit the construct.
485/// */
486/// } ident_t;
487enum IdentFieldIndex {
488 /// \brief might be used in Fortran
489 IdentField_Reserved_1,
490 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
491 IdentField_Flags,
492 /// \brief Not really used in Fortran any more
493 IdentField_Reserved_2,
494 /// \brief Source[4] in Fortran, do not use for C++
495 IdentField_Reserved_3,
496 /// \brief String describing the source location. The string is composed of
497 /// semi-colon separated fields which describe the source file, the function
498 /// and a pair of line numbers that delimit the construct.
499 IdentField_PSource
500};
501
502/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
503/// the enum sched_type in kmp.h).
504enum OpenMPSchedType {
505 /// \brief Lower bound for default (unordered) versions.
506 OMP_sch_lower = 32,
507 OMP_sch_static_chunked = 33,
508 OMP_sch_static = 34,
509 OMP_sch_dynamic_chunked = 35,
510 OMP_sch_guided_chunked = 36,
511 OMP_sch_runtime = 37,
512 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000513 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000514 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000515 /// \brief Lower bound for 'ordered' versions.
516 OMP_ord_lower = 64,
517 OMP_ord_static_chunked = 65,
518 OMP_ord_static = 66,
519 OMP_ord_dynamic_chunked = 67,
520 OMP_ord_guided_chunked = 68,
521 OMP_ord_runtime = 69,
522 OMP_ord_auto = 70,
523 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000524 /// \brief dist_schedule types
525 OMP_dist_sch_static_chunked = 91,
526 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000527 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
528 /// Set if the monotonic schedule modifier was present.
529 OMP_sch_modifier_monotonic = (1 << 29),
530 /// Set if the nonmonotonic schedule modifier was present.
531 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000532};
533
534enum OpenMPRTLFunction {
535 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
536 /// kmpc_micro microtask, ...);
537 OMPRTL__kmpc_fork_call,
538 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
539 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
540 OMPRTL__kmpc_threadprivate_cached,
541 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
542 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
543 OMPRTL__kmpc_threadprivate_register,
544 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
545 OMPRTL__kmpc_global_thread_num,
546 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
547 // kmp_critical_name *crit);
548 OMPRTL__kmpc_critical,
549 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
550 // global_tid, kmp_critical_name *crit, uintptr_t hint);
551 OMPRTL__kmpc_critical_with_hint,
552 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
553 // kmp_critical_name *crit);
554 OMPRTL__kmpc_end_critical,
555 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
556 // global_tid);
557 OMPRTL__kmpc_cancel_barrier,
558 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
559 OMPRTL__kmpc_barrier,
560 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
561 OMPRTL__kmpc_for_static_fini,
562 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
563 // global_tid);
564 OMPRTL__kmpc_serialized_parallel,
565 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
566 // global_tid);
567 OMPRTL__kmpc_end_serialized_parallel,
568 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
569 // kmp_int32 num_threads);
570 OMPRTL__kmpc_push_num_threads,
571 // Call to void __kmpc_flush(ident_t *loc);
572 OMPRTL__kmpc_flush,
573 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
574 OMPRTL__kmpc_master,
575 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
576 OMPRTL__kmpc_end_master,
577 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
578 // int end_part);
579 OMPRTL__kmpc_omp_taskyield,
580 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
581 OMPRTL__kmpc_single,
582 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
583 OMPRTL__kmpc_end_single,
584 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
585 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
586 // kmp_routine_entry_t *task_entry);
587 OMPRTL__kmpc_omp_task_alloc,
588 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
589 // new_task);
590 OMPRTL__kmpc_omp_task,
591 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
592 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
593 // kmp_int32 didit);
594 OMPRTL__kmpc_copyprivate,
595 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
596 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
597 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
598 OMPRTL__kmpc_reduce,
599 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
600 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
601 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
602 // *lck);
603 OMPRTL__kmpc_reduce_nowait,
604 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
605 // kmp_critical_name *lck);
606 OMPRTL__kmpc_end_reduce,
607 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
608 // kmp_critical_name *lck);
609 OMPRTL__kmpc_end_reduce_nowait,
610 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
611 // kmp_task_t * new_task);
612 OMPRTL__kmpc_omp_task_begin_if0,
613 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
614 // kmp_task_t * new_task);
615 OMPRTL__kmpc_omp_task_complete_if0,
616 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
617 OMPRTL__kmpc_ordered,
618 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
619 OMPRTL__kmpc_end_ordered,
620 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
621 // global_tid);
622 OMPRTL__kmpc_omp_taskwait,
623 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
624 OMPRTL__kmpc_taskgroup,
625 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
626 OMPRTL__kmpc_end_taskgroup,
627 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
628 // int proc_bind);
629 OMPRTL__kmpc_push_proc_bind,
630 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
632 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_task_with_deps,
634 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
635 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
636 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
637 OMPRTL__kmpc_omp_wait_deps,
638 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
639 // global_tid, kmp_int32 cncl_kind);
640 OMPRTL__kmpc_cancellationpoint,
641 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
642 // kmp_int32 cncl_kind);
643 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000644 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
645 // kmp_int32 num_teams, kmp_int32 thread_limit);
646 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000647 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
648 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000649 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000650 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
651 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
652 // sched, kmp_uint64 grainsize, void *task_dup);
653 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000654 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
655 // num_dims, struct kmp_dim *dims);
656 OMPRTL__kmpc_doacross_init,
657 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
658 OMPRTL__kmpc_doacross_fini,
659 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
660 // *vec);
661 OMPRTL__kmpc_doacross_post,
662 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
663 // *vec);
664 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000665 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
666 // *data);
667 OMPRTL__kmpc_task_reduction_init,
668 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
669 // *d);
670 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671
672 //
673 // Offloading related calls
674 //
George Rokos63bc9d62017-11-21 18:25:12 +0000675 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
676 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000677 // *arg_types);
678 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000679 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
680 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
681 // *arg_types);
682 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000683 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
684 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
685 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000686 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000687 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
688 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
689 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
690 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000691 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
692 OMPRTL__tgt_register_lib,
693 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
694 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000695 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
696 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000697 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000698 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
699 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
700 // *arg_types);
701 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000702 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
703 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000704 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000705 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
706 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
707 // *arg_types);
708 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000709 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
710 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000711 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000712 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
713 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
714 // *arg_types);
715 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000716};
717
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000718/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
719/// region.
720class CleanupTy final : public EHScopeStack::Cleanup {
721 PrePostActionTy *Action;
722
723public:
724 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
725 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
726 if (!CGF.HaveInsertPoint())
727 return;
728 Action->Exit(CGF);
729 }
730};
731
Hans Wennborg7eb54642015-09-10 17:07:54 +0000732} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000733
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000734void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
735 CodeGenFunction::RunCleanupsScope Scope(CGF);
736 if (PrePostAction) {
737 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
738 Callback(CodeGen, CGF, *PrePostAction);
739 } else {
740 PrePostActionTy Action;
741 Callback(CodeGen, CGF, Action);
742 }
743}
744
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000745/// Check if the combiner is a call to UDR combiner and if it is so return the
746/// UDR decl used for reduction.
747static const OMPDeclareReductionDecl *
748getReductionInit(const Expr *ReductionOp) {
749 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
750 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
751 if (auto *DRE =
752 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
753 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
754 return DRD;
755 return nullptr;
756}
757
758static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
759 const OMPDeclareReductionDecl *DRD,
760 const Expr *InitOp,
761 Address Private, Address Original,
762 QualType Ty) {
763 if (DRD->getInitializer()) {
764 std::pair<llvm::Function *, llvm::Function *> Reduction =
765 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
766 auto *CE = cast<CallExpr>(InitOp);
767 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
768 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
769 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
770 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
771 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
772 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
773 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
774 [=]() -> Address { return Private; });
775 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
776 [=]() -> Address { return Original; });
777 (void)PrivateScope.Privatize();
778 RValue Func = RValue::get(Reduction.second);
779 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
780 CGF.EmitIgnoredExpr(InitOp);
781 } else {
782 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
783 auto *GV = new llvm::GlobalVariable(
784 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
785 llvm::GlobalValue::PrivateLinkage, Init, ".init");
786 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
787 RValue InitRVal;
788 switch (CGF.getEvaluationKind(Ty)) {
789 case TEK_Scalar:
790 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
791 break;
792 case TEK_Complex:
793 InitRVal =
794 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
795 break;
796 case TEK_Aggregate:
797 InitRVal = RValue::getAggregate(LV.getAddress());
798 break;
799 }
800 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
801 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
802 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
803 /*IsInitializer=*/false);
804 }
805}
806
807/// \brief Emit initialization of arrays of complex types.
808/// \param DestAddr Address of the array.
809/// \param Type Type of array.
810/// \param Init Initial expression of array.
811/// \param SrcAddr Address of the original array.
812static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000813 QualType Type, bool EmitDeclareReductionInit,
814 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000815 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000816 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000817 // Perform element-by-element initialization.
818 QualType ElementTy;
819
820 // Drill down to the base element type on both arrays.
821 auto ArrayTy = Type->getAsArrayTypeUnsafe();
822 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
823 DestAddr =
824 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
825 if (DRD)
826 SrcAddr =
827 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
828
829 llvm::Value *SrcBegin = nullptr;
830 if (DRD)
831 SrcBegin = SrcAddr.getPointer();
832 auto DestBegin = DestAddr.getPointer();
833 // Cast from pointer to array type to pointer to single element.
834 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
835 // The basic structure here is a while-do loop.
836 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
837 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
838 auto IsEmpty =
839 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
840 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
841
842 // Enter the loop body, making that address the current address.
843 auto EntryBB = CGF.Builder.GetInsertBlock();
844 CGF.EmitBlock(BodyBB);
845
846 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
847
848 llvm::PHINode *SrcElementPHI = nullptr;
849 Address SrcElementCurrent = Address::invalid();
850 if (DRD) {
851 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
852 "omp.arraycpy.srcElementPast");
853 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
854 SrcElementCurrent =
855 Address(SrcElementPHI,
856 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
857 }
858 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
859 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
860 DestElementPHI->addIncoming(DestBegin, EntryBB);
861 Address DestElementCurrent =
862 Address(DestElementPHI,
863 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
864
865 // Emit copy.
866 {
867 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000868 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000869 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
870 SrcElementCurrent, ElementTy);
871 } else
872 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
873 /*IsInitializer=*/false);
874 }
875
876 if (DRD) {
877 // Shift the address forward by one element.
878 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
879 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
880 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
881 }
882
883 // Shift the address forward by one element.
884 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
885 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
886 // Check whether we've reached the end.
887 auto Done =
888 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
889 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
890 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
891
892 // Done.
893 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
894}
895
896LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000897 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000898}
899
900LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
901 const Expr *E) {
902 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
903 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
904 return LValue();
905}
906
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000907void ReductionCodeGen::emitAggregateInitialization(
908 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
909 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000910 // Emit VarDecl with copy init for arrays.
911 // Get the address of the original variable captured in current
912 // captured region.
913 auto *PrivateVD =
914 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000915 bool EmitDeclareReductionInit =
916 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000917 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000918 EmitDeclareReductionInit,
919 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
920 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000921 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000922}
923
924ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
925 ArrayRef<const Expr *> Privates,
926 ArrayRef<const Expr *> ReductionOps) {
927 ClausesData.reserve(Shareds.size());
928 SharedAddresses.reserve(Shareds.size());
929 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000931 auto IPriv = Privates.begin();
932 auto IRed = ReductionOps.begin();
933 for (const auto *Ref : Shareds) {
934 ClausesData.emplace_back(Ref, *IPriv, *IRed);
935 std::advance(IPriv, 1);
936 std::advance(IRed, 1);
937 }
938}
939
940void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
941 assert(SharedAddresses.size() == N &&
942 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000943 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
944 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
945 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000946}
947
948void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
949 auto *PrivateVD =
950 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
951 QualType PrivateType = PrivateVD->getType();
952 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000953 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000954 Sizes.emplace_back(
955 CGF.getTypeSize(
956 SharedAddresses[N].first.getType().getNonReferenceType()),
957 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000958 return;
959 }
960 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000961 llvm::Value *SizeInChars;
962 llvm::Type *ElemType =
963 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
964 ->getElementType();
965 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000966 if (AsArraySection) {
967 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
968 SharedAddresses[N].first.getPointer());
969 Size = CGF.Builder.CreateNUWAdd(
970 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000971 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000972 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000973 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000974 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000975 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000976 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000978 CodeGenFunction::OpaqueValueMapping OpaqueMap(
979 CGF,
980 cast<OpaqueValueExpr>(
981 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
982 RValue::get(Size));
983 CGF.EmitVariablyModifiedType(PrivateType);
984}
985
986void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
987 llvm::Value *Size) {
988 auto *PrivateVD =
989 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
990 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000991 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000992 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000993 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000994 "items.");
995 return;
996 }
997 CodeGenFunction::OpaqueValueMapping OpaqueMap(
998 CGF,
999 cast<OpaqueValueExpr>(
1000 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1001 RValue::get(Size));
1002 CGF.EmitVariablyModifiedType(PrivateType);
1003}
1004
1005void ReductionCodeGen::emitInitialization(
1006 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1007 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1008 assert(SharedAddresses.size() > N && "No variable was generated");
1009 auto *PrivateVD =
1010 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1011 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1012 QualType PrivateType = PrivateVD->getType();
1013 PrivateAddr = CGF.Builder.CreateElementBitCast(
1014 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1015 QualType SharedType = SharedAddresses[N].first.getType();
1016 SharedLVal = CGF.MakeAddrLValue(
1017 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1018 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001019 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001020 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001021 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001022 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001023 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1024 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1025 PrivateAddr, SharedLVal.getAddress(),
1026 SharedLVal.getType());
1027 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1028 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1029 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1030 PrivateVD->getType().getQualifiers(),
1031 /*IsInitializer=*/false);
1032 }
1033}
1034
1035bool ReductionCodeGen::needCleanups(unsigned N) {
1036 auto *PrivateVD =
1037 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1038 QualType PrivateType = PrivateVD->getType();
1039 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1040 return DTorKind != QualType::DK_none;
1041}
1042
1043void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1044 Address PrivateAddr) {
1045 auto *PrivateVD =
1046 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1047 QualType PrivateType = PrivateVD->getType();
1048 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1049 if (needCleanups(N)) {
1050 PrivateAddr = CGF.Builder.CreateElementBitCast(
1051 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1052 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1053 }
1054}
1055
1056static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1057 LValue BaseLV) {
1058 BaseTy = BaseTy.getNonReferenceType();
1059 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1060 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1061 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1062 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1063 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001064 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1065 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001066 }
1067 BaseTy = BaseTy->getPointeeType();
1068 }
1069 return CGF.MakeAddrLValue(
1070 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1071 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001072 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001073 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001074}
1075
1076static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1077 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1078 llvm::Value *Addr) {
1079 Address Tmp = Address::invalid();
1080 Address TopTmp = Address::invalid();
1081 Address MostTopTmp = Address::invalid();
1082 BaseTy = BaseTy.getNonReferenceType();
1083 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1084 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1085 Tmp = CGF.CreateMemTemp(BaseTy);
1086 if (TopTmp.isValid())
1087 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1088 else
1089 MostTopTmp = Tmp;
1090 TopTmp = Tmp;
1091 BaseTy = BaseTy->getPointeeType();
1092 }
1093 llvm::Type *Ty = BaseLVType;
1094 if (Tmp.isValid())
1095 Ty = Tmp.getElementType();
1096 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1097 if (Tmp.isValid()) {
1098 CGF.Builder.CreateStore(Addr, Tmp);
1099 return MostTopTmp;
1100 }
1101 return Address(Addr, BaseLVAlignment);
1102}
1103
1104Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1105 Address PrivateAddr) {
1106 const DeclRefExpr *DE;
1107 const VarDecl *OrigVD = nullptr;
1108 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1109 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1110 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1111 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1112 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1113 Base = TempASE->getBase()->IgnoreParenImpCasts();
1114 DE = cast<DeclRefExpr>(Base);
1115 OrigVD = cast<VarDecl>(DE->getDecl());
1116 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1117 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1118 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1119 Base = TempASE->getBase()->IgnoreParenImpCasts();
1120 DE = cast<DeclRefExpr>(Base);
1121 OrigVD = cast<VarDecl>(DE->getDecl());
1122 }
1123 if (OrigVD) {
1124 BaseDecls.emplace_back(OrigVD);
1125 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1126 LValue BaseLValue =
1127 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1128 OriginalBaseLValue);
1129 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1130 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001131 llvm::Value *PrivatePointer =
1132 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1133 PrivateAddr.getPointer(),
1134 SharedAddresses[N].first.getAddress().getType());
1135 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001136 return castToBase(CGF, OrigVD->getType(),
1137 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001138 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001139 OriginalBaseLValue.getAlignment(), Ptr);
1140 }
1141 BaseDecls.emplace_back(
1142 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1143 return PrivateAddr;
1144}
1145
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001146bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1147 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1148 return DRD && DRD->getInitializer();
1149}
1150
Alexey Bataev18095712014-10-10 12:19:54 +00001151LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001152 return CGF.EmitLoadOfPointerLValue(
1153 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1154 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001155}
1156
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001157void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001158 if (!CGF.HaveInsertPoint())
1159 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001160 // 1.2.2 OpenMP Language Terminology
1161 // Structured block - An executable statement with a single entry at the
1162 // top and a single exit at the bottom.
1163 // The point of exit cannot be a branch out of the structured block.
1164 // longjmp() and throw() must not violate the entry/exit criteria.
1165 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001166 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001168}
1169
Alexey Bataev62b63b12015-03-10 07:28:44 +00001170LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1171 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001172 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1173 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001174 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001175}
1176
Alexey Bataev9959db52014-05-06 10:08:46 +00001177CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001178 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001179 IdentTy = llvm::StructType::create(
1180 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1181 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001182 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001183 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001184
1185 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001186}
1187
Alexey Bataev91797552015-03-18 04:13:55 +00001188void CGOpenMPRuntime::clear() {
1189 InternalVars.clear();
1190}
1191
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001192static llvm::Function *
1193emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1194 const Expr *CombinerInitializer, const VarDecl *In,
1195 const VarDecl *Out, bool IsCombiner) {
1196 // void .omp_combiner.(Ty *in, Ty *out);
1197 auto &C = CGM.getContext();
1198 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1199 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001200 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001201 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001202 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001203 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001204 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001205 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001206 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001207 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001208 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1209 auto *Fn = llvm::Function::Create(
1210 FnTy, llvm::GlobalValue::InternalLinkage,
1211 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1212 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001213 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001214 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001215 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001216 CodeGenFunction CGF(CGM);
1217 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1218 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001219 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1220 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001221 CodeGenFunction::OMPPrivateScope Scope(CGF);
1222 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1223 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1224 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1225 .getAddress();
1226 });
1227 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1228 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1229 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1230 .getAddress();
1231 });
1232 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001233 if (!IsCombiner && Out->hasInit() &&
1234 !CGF.isTrivialInitializer(Out->getInit())) {
1235 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1236 Out->getType().getQualifiers(),
1237 /*IsInitializer=*/true);
1238 }
1239 if (CombinerInitializer)
1240 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001241 Scope.ForceCleanup();
1242 CGF.FinishFunction();
1243 return Fn;
1244}
1245
1246void CGOpenMPRuntime::emitUserDefinedReduction(
1247 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1248 if (UDRMap.count(D) > 0)
1249 return;
1250 auto &C = CGM.getContext();
1251 if (!In || !Out) {
1252 In = &C.Idents.get("omp_in");
1253 Out = &C.Idents.get("omp_out");
1254 }
1255 llvm::Function *Combiner = emitCombinerOrInitializer(
1256 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1257 cast<VarDecl>(D->lookup(Out).front()),
1258 /*IsCombiner=*/true);
1259 llvm::Function *Initializer = nullptr;
1260 if (auto *Init = D->getInitializer()) {
1261 if (!Priv || !Orig) {
1262 Priv = &C.Idents.get("omp_priv");
1263 Orig = &C.Idents.get("omp_orig");
1264 }
1265 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001266 CGM, D->getType(),
1267 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1268 : nullptr,
1269 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001270 cast<VarDecl>(D->lookup(Priv).front()),
1271 /*IsCombiner=*/false);
1272 }
1273 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1274 if (CGF) {
1275 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1276 Decls.second.push_back(D);
1277 }
1278}
1279
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001280std::pair<llvm::Function *, llvm::Function *>
1281CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1282 auto I = UDRMap.find(D);
1283 if (I != UDRMap.end())
1284 return I->second;
1285 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1286 return UDRMap.lookup(D);
1287}
1288
John McCall7f416cc2015-09-08 08:05:57 +00001289// Layout information for ident_t.
1290static CharUnits getIdentAlign(CodeGenModule &CGM) {
1291 return CGM.getPointerAlign();
1292}
1293static CharUnits getIdentSize(CodeGenModule &CGM) {
1294 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1295 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1296}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001297static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001298 // All the fields except the last are i32, so this works beautifully.
1299 return unsigned(Field) * CharUnits::fromQuantity(4);
1300}
1301static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001302 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001303 const llvm::Twine &Name = "") {
1304 auto Offset = getOffsetOfIdentField(Field);
1305 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1306}
1307
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001308static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1309 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1310 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1311 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001312 assert(ThreadIDVar->getType()->isPointerType() &&
1313 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001314 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001315 bool HasCancel = false;
1316 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1317 HasCancel = OPD->hasCancel();
1318 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1319 HasCancel = OPSD->hasCancel();
1320 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1321 HasCancel = OPFD->hasCancel();
Alexey Bataev2139ed62017-11-16 18:20:21 +00001322 else if (auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1323 HasCancel = OPFD->hasCancel();
Alexey Bataev10a54312017-11-27 16:54:08 +00001324 else if (auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1325 HasCancel = OPFD->hasCancel();
1326 else if (auto *OPFD = dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1327 HasCancel = OPFD->hasCancel();
1328 else if (auto *OPFD =
1329 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1330 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001331 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001332 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001333 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001334 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001335}
1336
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001337llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1338 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1339 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1340 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1341 return emitParallelOrTeamsOutlinedFunction(
1342 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1343}
1344
1345llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1346 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1347 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1348 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1349 return emitParallelOrTeamsOutlinedFunction(
1350 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1351}
1352
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001353llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1354 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001355 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1356 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1357 bool Tied, unsigned &NumberOfParts) {
1358 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1359 PrePostActionTy &) {
1360 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1361 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1362 llvm::Value *TaskArgs[] = {
1363 UpLoc, ThreadID,
1364 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1365 TaskTVar->getType()->castAs<PointerType>())
1366 .getPointer()};
1367 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1368 };
1369 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1370 UntiedCodeGen);
1371 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001372 assert(!ThreadIDVar->getType()->isPointerType() &&
1373 "thread id variable must be of type kmp_int32 for tasks");
1374 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001375 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001376 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001377 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1378 InnermostKind,
1379 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001380 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001381 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1382 if (!Tied)
1383 NumberOfParts = Action.getNumberOfParts();
1384 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001385}
1386
Alexey Bataev50b3c952016-02-19 10:38:26 +00001387Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001388 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001389 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001390 if (!Entry) {
1391 if (!DefaultOpenMPPSource) {
1392 // Initialize default location for psource field of ident_t structure of
1393 // all ident_t objects. Format is ";file;function;line;column;;".
1394 // Taken from
1395 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1396 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001397 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001398 DefaultOpenMPPSource =
1399 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1400 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001401
John McCall23c9dc62016-11-28 22:18:27 +00001402 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001403 auto fields = builder.beginStruct(IdentTy);
1404 fields.addInt(CGM.Int32Ty, 0);
1405 fields.addInt(CGM.Int32Ty, Flags);
1406 fields.addInt(CGM.Int32Ty, 0);
1407 fields.addInt(CGM.Int32Ty, 0);
1408 fields.add(DefaultOpenMPPSource);
1409 auto DefaultOpenMPLocation =
1410 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1411 llvm::GlobalValue::PrivateLinkage);
1412 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1413
John McCall7f416cc2015-09-08 08:05:57 +00001414 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001415 }
John McCall7f416cc2015-09-08 08:05:57 +00001416 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001417}
1418
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001419llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1420 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001421 unsigned Flags) {
1422 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001423 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001424 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001425 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001426 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001427
1428 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1429
John McCall7f416cc2015-09-08 08:05:57 +00001430 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001431 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1432 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001433 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1434
Alexander Musmanc6388682014-12-15 07:07:06 +00001435 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1436 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001437 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001438 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001439 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1440 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001441 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001442 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001443 LocValue = AI;
1444
1445 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1446 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001447 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001448 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001449 }
1450
1451 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001452 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001453
Alexey Bataevf002aca2014-05-30 05:48:40 +00001454 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1455 if (OMPDebugLoc == nullptr) {
1456 SmallString<128> Buffer2;
1457 llvm::raw_svector_ostream OS2(Buffer2);
1458 // Build debug location
1459 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1460 OS2 << ";" << PLoc.getFilename() << ";";
1461 if (const FunctionDecl *FD =
1462 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1463 OS2 << FD->getQualifiedNameAsString();
1464 }
1465 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1466 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1467 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001468 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001469 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001470 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1471
John McCall7f416cc2015-09-08 08:05:57 +00001472 // Our callers always pass this to a runtime function, so for
1473 // convenience, go ahead and return a naked pointer.
1474 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001475}
1476
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001477llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1478 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001479 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1480
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001481 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001482 // Check whether we've already cached a load of the thread id in this
1483 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001484 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001485 if (I != OpenMPLocThreadIDMap.end()) {
1486 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001487 if (ThreadID != nullptr)
1488 return ThreadID;
1489 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001490 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001491 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1492 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001493 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001494 if (auto *OMPRegionInfo =
1495 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1496 if (OMPRegionInfo->getThreadIDVariable()) {
1497 // Check if this an outlined function with thread id passed as argument.
1498 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1499 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1500 // If value loaded in entry block, cache it and use it everywhere in
1501 // function.
1502 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1503 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1504 Elem.second.ThreadID = ThreadID;
1505 }
1506 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001507 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001508 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001509 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001510
1511 // This is not an outlined function region - need to call __kmpc_int32
1512 // kmpc_global_thread_num(ident_t *loc).
1513 // Generate thread id value and cache this value for use across the
1514 // function.
1515 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1516 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001517 auto *Call = CGF.Builder.CreateCall(
1518 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1519 emitUpdateLocation(CGF, Loc));
1520 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001521 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001522 Elem.second.ThreadID = Call;
1523 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001524}
1525
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001526void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001527 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001528 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1529 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001530 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1531 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1532 UDRMap.erase(D);
1533 }
1534 FunctionUDRMap.erase(CGF.CurFn);
1535 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001536}
1537
1538llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001539 if (!IdentTy) {
1540 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001541 return llvm::PointerType::getUnqual(IdentTy);
1542}
1543
1544llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001545 if (!Kmpc_MicroTy) {
1546 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1547 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1548 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1549 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1550 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001551 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1552}
1553
1554llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001555CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001556 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001557 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001558 case OMPRTL__kmpc_fork_call: {
1559 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1560 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001561 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1562 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001563 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001564 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001565 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1566 break;
1567 }
1568 case OMPRTL__kmpc_global_thread_num: {
1569 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001570 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001571 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001572 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001573 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1574 break;
1575 }
Alexey Bataev97720002014-11-11 04:05:39 +00001576 case OMPRTL__kmpc_threadprivate_cached: {
1577 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1578 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1580 CGM.VoidPtrTy, CGM.SizeTy,
1581 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1582 llvm::FunctionType *FnTy =
1583 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1584 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1585 break;
1586 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001587 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001588 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1589 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001590 llvm::Type *TypeParams[] = {
1591 getIdentTyPointerTy(), CGM.Int32Ty,
1592 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1593 llvm::FunctionType *FnTy =
1594 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1595 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1596 break;
1597 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001598 case OMPRTL__kmpc_critical_with_hint: {
1599 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1600 // kmp_critical_name *crit, uintptr_t hint);
1601 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1602 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1603 CGM.IntPtrTy};
1604 llvm::FunctionType *FnTy =
1605 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1606 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1607 break;
1608 }
Alexey Bataev97720002014-11-11 04:05:39 +00001609 case OMPRTL__kmpc_threadprivate_register: {
1610 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1611 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1612 // typedef void *(*kmpc_ctor)(void *);
1613 auto KmpcCtorTy =
1614 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1615 /*isVarArg*/ false)->getPointerTo();
1616 // typedef void *(*kmpc_cctor)(void *, void *);
1617 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1618 auto KmpcCopyCtorTy =
1619 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1620 /*isVarArg*/ false)->getPointerTo();
1621 // typedef void (*kmpc_dtor)(void *);
1622 auto KmpcDtorTy =
1623 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1624 ->getPointerTo();
1625 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1626 KmpcCopyCtorTy, KmpcDtorTy};
1627 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1628 /*isVarArg*/ false);
1629 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1630 break;
1631 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001632 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001633 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1634 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001635 llvm::Type *TypeParams[] = {
1636 getIdentTyPointerTy(), CGM.Int32Ty,
1637 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1638 llvm::FunctionType *FnTy =
1639 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1641 break;
1642 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001643 case OMPRTL__kmpc_cancel_barrier: {
1644 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1645 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001646 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1647 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001648 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1649 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001650 break;
1651 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001652 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001653 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001654 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1655 llvm::FunctionType *FnTy =
1656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1657 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1658 break;
1659 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001660 case OMPRTL__kmpc_for_static_fini: {
1661 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1662 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1663 llvm::FunctionType *FnTy =
1664 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1665 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1666 break;
1667 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001668 case OMPRTL__kmpc_push_num_threads: {
1669 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1670 // kmp_int32 num_threads)
1671 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1672 CGM.Int32Ty};
1673 llvm::FunctionType *FnTy =
1674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1676 break;
1677 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001678 case OMPRTL__kmpc_serialized_parallel: {
1679 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1680 // global_tid);
1681 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1682 llvm::FunctionType *FnTy =
1683 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1684 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1685 break;
1686 }
1687 case OMPRTL__kmpc_end_serialized_parallel: {
1688 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1689 // global_tid);
1690 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1691 llvm::FunctionType *FnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1694 break;
1695 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001696 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001697 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001698 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1699 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001700 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001701 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1702 break;
1703 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001704 case OMPRTL__kmpc_master: {
1705 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1706 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1707 llvm::FunctionType *FnTy =
1708 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1709 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1710 break;
1711 }
1712 case OMPRTL__kmpc_end_master: {
1713 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1714 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1715 llvm::FunctionType *FnTy =
1716 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1717 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1718 break;
1719 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001720 case OMPRTL__kmpc_omp_taskyield: {
1721 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1722 // int end_part);
1723 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1724 llvm::FunctionType *FnTy =
1725 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1726 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1727 break;
1728 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001729 case OMPRTL__kmpc_single: {
1730 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1731 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1732 llvm::FunctionType *FnTy =
1733 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1734 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1735 break;
1736 }
1737 case OMPRTL__kmpc_end_single: {
1738 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1740 llvm::FunctionType *FnTy =
1741 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1743 break;
1744 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001745 case OMPRTL__kmpc_omp_task_alloc: {
1746 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1747 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1748 // kmp_routine_entry_t *task_entry);
1749 assert(KmpRoutineEntryPtrTy != nullptr &&
1750 "Type kmp_routine_entry_t must be created.");
1751 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1752 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1753 // Return void * and then cast to particular kmp_task_t type.
1754 llvm::FunctionType *FnTy =
1755 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1756 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1757 break;
1758 }
1759 case OMPRTL__kmpc_omp_task: {
1760 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1761 // *new_task);
1762 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1763 CGM.VoidPtrTy};
1764 llvm::FunctionType *FnTy =
1765 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1766 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1767 break;
1768 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001769 case OMPRTL__kmpc_copyprivate: {
1770 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001771 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001772 // kmp_int32 didit);
1773 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1774 auto *CpyFnTy =
1775 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001776 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001777 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1778 CGM.Int32Ty};
1779 llvm::FunctionType *FnTy =
1780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1781 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1782 break;
1783 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001784 case OMPRTL__kmpc_reduce: {
1785 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1786 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1787 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1788 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1789 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1790 /*isVarArg=*/false);
1791 llvm::Type *TypeParams[] = {
1792 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1793 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1794 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1795 llvm::FunctionType *FnTy =
1796 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1797 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1798 break;
1799 }
1800 case OMPRTL__kmpc_reduce_nowait: {
1801 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1802 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1803 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1804 // *lck);
1805 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1806 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1807 /*isVarArg=*/false);
1808 llvm::Type *TypeParams[] = {
1809 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1810 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1811 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1812 llvm::FunctionType *FnTy =
1813 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1814 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1815 break;
1816 }
1817 case OMPRTL__kmpc_end_reduce: {
1818 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1819 // kmp_critical_name *lck);
1820 llvm::Type *TypeParams[] = {
1821 getIdentTyPointerTy(), CGM.Int32Ty,
1822 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1823 llvm::FunctionType *FnTy =
1824 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1825 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1826 break;
1827 }
1828 case OMPRTL__kmpc_end_reduce_nowait: {
1829 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1830 // kmp_critical_name *lck);
1831 llvm::Type *TypeParams[] = {
1832 getIdentTyPointerTy(), CGM.Int32Ty,
1833 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1834 llvm::FunctionType *FnTy =
1835 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1836 RTLFn =
1837 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1838 break;
1839 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001840 case OMPRTL__kmpc_omp_task_begin_if0: {
1841 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1842 // *new_task);
1843 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1844 CGM.VoidPtrTy};
1845 llvm::FunctionType *FnTy =
1846 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1847 RTLFn =
1848 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1849 break;
1850 }
1851 case OMPRTL__kmpc_omp_task_complete_if0: {
1852 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1853 // *new_task);
1854 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1855 CGM.VoidPtrTy};
1856 llvm::FunctionType *FnTy =
1857 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1858 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1859 /*Name=*/"__kmpc_omp_task_complete_if0");
1860 break;
1861 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001862 case OMPRTL__kmpc_ordered: {
1863 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1864 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1865 llvm::FunctionType *FnTy =
1866 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1867 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1868 break;
1869 }
1870 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001871 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001872 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1873 llvm::FunctionType *FnTy =
1874 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1875 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1876 break;
1877 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001878 case OMPRTL__kmpc_omp_taskwait: {
1879 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1880 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1881 llvm::FunctionType *FnTy =
1882 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1883 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1884 break;
1885 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001886 case OMPRTL__kmpc_taskgroup: {
1887 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1888 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1889 llvm::FunctionType *FnTy =
1890 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1891 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1892 break;
1893 }
1894 case OMPRTL__kmpc_end_taskgroup: {
1895 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1896 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1897 llvm::FunctionType *FnTy =
1898 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1899 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1900 break;
1901 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001902 case OMPRTL__kmpc_push_proc_bind: {
1903 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1904 // int proc_bind)
1905 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1906 llvm::FunctionType *FnTy =
1907 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1908 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1909 break;
1910 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001911 case OMPRTL__kmpc_omp_task_with_deps: {
1912 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1913 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1914 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1915 llvm::Type *TypeParams[] = {
1916 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1917 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1918 llvm::FunctionType *FnTy =
1919 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1920 RTLFn =
1921 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1922 break;
1923 }
1924 case OMPRTL__kmpc_omp_wait_deps: {
1925 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1926 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1927 // kmp_depend_info_t *noalias_dep_list);
1928 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1929 CGM.Int32Ty, CGM.VoidPtrTy,
1930 CGM.Int32Ty, CGM.VoidPtrTy};
1931 llvm::FunctionType *FnTy =
1932 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1933 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1934 break;
1935 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001936 case OMPRTL__kmpc_cancellationpoint: {
1937 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1938 // global_tid, kmp_int32 cncl_kind)
1939 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1940 llvm::FunctionType *FnTy =
1941 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1942 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1943 break;
1944 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001945 case OMPRTL__kmpc_cancel: {
1946 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1947 // kmp_int32 cncl_kind)
1948 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1949 llvm::FunctionType *FnTy =
1950 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1952 break;
1953 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001954 case OMPRTL__kmpc_push_num_teams: {
1955 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1956 // kmp_int32 num_teams, kmp_int32 num_threads)
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1958 CGM.Int32Ty};
1959 llvm::FunctionType *FnTy =
1960 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1961 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1962 break;
1963 }
1964 case OMPRTL__kmpc_fork_teams: {
1965 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1966 // microtask, ...);
1967 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1968 getKmpc_MicroPointerTy()};
1969 llvm::FunctionType *FnTy =
1970 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1971 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1972 break;
1973 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001974 case OMPRTL__kmpc_taskloop: {
1975 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1976 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1977 // sched, kmp_uint64 grainsize, void *task_dup);
1978 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1979 CGM.IntTy,
1980 CGM.VoidPtrTy,
1981 CGM.IntTy,
1982 CGM.Int64Ty->getPointerTo(),
1983 CGM.Int64Ty->getPointerTo(),
1984 CGM.Int64Ty,
1985 CGM.IntTy,
1986 CGM.IntTy,
1987 CGM.Int64Ty,
1988 CGM.VoidPtrTy};
1989 llvm::FunctionType *FnTy =
1990 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1991 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1992 break;
1993 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001994 case OMPRTL__kmpc_doacross_init: {
1995 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1996 // num_dims, struct kmp_dim *dims);
1997 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1998 CGM.Int32Ty,
1999 CGM.Int32Ty,
2000 CGM.VoidPtrTy};
2001 llvm::FunctionType *FnTy =
2002 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2003 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2004 break;
2005 }
2006 case OMPRTL__kmpc_doacross_fini: {
2007 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2008 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2009 llvm::FunctionType *FnTy =
2010 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2011 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2012 break;
2013 }
2014 case OMPRTL__kmpc_doacross_post: {
2015 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2016 // *vec);
2017 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2018 CGM.Int64Ty->getPointerTo()};
2019 llvm::FunctionType *FnTy =
2020 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2021 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2022 break;
2023 }
2024 case OMPRTL__kmpc_doacross_wait: {
2025 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2026 // *vec);
2027 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2028 CGM.Int64Ty->getPointerTo()};
2029 llvm::FunctionType *FnTy =
2030 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2031 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2032 break;
2033 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002034 case OMPRTL__kmpc_task_reduction_init: {
2035 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2036 // *data);
2037 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2038 llvm::FunctionType *FnTy =
2039 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2040 RTLFn =
2041 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2042 break;
2043 }
2044 case OMPRTL__kmpc_task_reduction_get_th_data: {
2045 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2046 // *d);
2047 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2048 llvm::FunctionType *FnTy =
2049 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2050 RTLFn = CGM.CreateRuntimeFunction(
2051 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2052 break;
2053 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002054 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002055 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2056 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002057 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002058 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002059 CGM.VoidPtrTy,
2060 CGM.Int32Ty,
2061 CGM.VoidPtrPtrTy,
2062 CGM.VoidPtrPtrTy,
2063 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002064 CGM.Int64Ty->getPointerTo()};
Samuel Antaobed3c462015-10-02 16:14:20 +00002065 llvm::FunctionType *FnTy =
2066 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2067 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2068 break;
2069 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002070 case OMPRTL__tgt_target_nowait: {
2071 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2072 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2073 // int64_t *arg_types);
2074 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2075 CGM.VoidPtrTy,
2076 CGM.Int32Ty,
2077 CGM.VoidPtrPtrTy,
2078 CGM.VoidPtrPtrTy,
2079 CGM.SizeTy->getPointerTo(),
2080 CGM.Int64Ty->getPointerTo()};
2081 llvm::FunctionType *FnTy =
2082 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2083 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2084 break;
2085 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002086 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002087 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002088 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002089 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2090 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002091 CGM.VoidPtrTy,
2092 CGM.Int32Ty,
2093 CGM.VoidPtrPtrTy,
2094 CGM.VoidPtrPtrTy,
2095 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002096 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002097 CGM.Int32Ty,
2098 CGM.Int32Ty};
2099 llvm::FunctionType *FnTy =
2100 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2101 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2102 break;
2103 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002104 case OMPRTL__tgt_target_teams_nowait: {
2105 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2106 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2107 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2108 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2109 CGM.VoidPtrTy,
2110 CGM.Int32Ty,
2111 CGM.VoidPtrPtrTy,
2112 CGM.VoidPtrPtrTy,
2113 CGM.SizeTy->getPointerTo(),
2114 CGM.Int64Ty->getPointerTo(),
2115 CGM.Int32Ty,
2116 CGM.Int32Ty};
2117 llvm::FunctionType *FnTy =
2118 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2119 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2120 break;
2121 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002122 case OMPRTL__tgt_register_lib: {
2123 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2124 QualType ParamTy =
2125 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2126 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2127 llvm::FunctionType *FnTy =
2128 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2129 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2130 break;
2131 }
2132 case OMPRTL__tgt_unregister_lib: {
2133 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2134 QualType ParamTy =
2135 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2136 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2137 llvm::FunctionType *FnTy =
2138 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2139 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2140 break;
2141 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002142 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002143 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2144 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2145 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002146 CGM.Int32Ty,
2147 CGM.VoidPtrPtrTy,
2148 CGM.VoidPtrPtrTy,
2149 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002150 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002151 llvm::FunctionType *FnTy =
2152 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2153 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2154 break;
2155 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002156 case OMPRTL__tgt_target_data_begin_nowait: {
2157 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2158 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2159 // *arg_types);
2160 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2161 CGM.Int32Ty,
2162 CGM.VoidPtrPtrTy,
2163 CGM.VoidPtrPtrTy,
2164 CGM.SizeTy->getPointerTo(),
2165 CGM.Int64Ty->getPointerTo()};
2166 auto *FnTy =
2167 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2168 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2169 break;
2170 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002171 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002172 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2173 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2174 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002175 CGM.Int32Ty,
2176 CGM.VoidPtrPtrTy,
2177 CGM.VoidPtrPtrTy,
2178 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002179 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002180 llvm::FunctionType *FnTy =
2181 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2182 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2183 break;
2184 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002185 case OMPRTL__tgt_target_data_end_nowait: {
2186 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2187 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2188 // *arg_types);
2189 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2190 CGM.Int32Ty,
2191 CGM.VoidPtrPtrTy,
2192 CGM.VoidPtrPtrTy,
2193 CGM.SizeTy->getPointerTo(),
2194 CGM.Int64Ty->getPointerTo()};
2195 auto *FnTy =
2196 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2198 break;
2199 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002200 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002201 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2202 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2203 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002204 CGM.Int32Ty,
2205 CGM.VoidPtrPtrTy,
2206 CGM.VoidPtrPtrTy,
2207 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002208 CGM.Int64Ty->getPointerTo()};
Samuel Antao8d2d7302016-05-26 18:30:22 +00002209 llvm::FunctionType *FnTy =
2210 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2211 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2212 break;
2213 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002214 case OMPRTL__tgt_target_data_update_nowait: {
2215 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2216 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2217 // *arg_types);
2218 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2219 CGM.Int32Ty,
2220 CGM.VoidPtrPtrTy,
2221 CGM.VoidPtrPtrTy,
2222 CGM.SizeTy->getPointerTo(),
2223 CGM.Int64Ty->getPointerTo()};
2224 auto *FnTy =
2225 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2226 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2227 break;
2228 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002229 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002230 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002231 return RTLFn;
2232}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002233
Alexander Musman21212e42015-03-13 10:38:23 +00002234llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2235 bool IVSigned) {
2236 assert((IVSize == 32 || IVSize == 64) &&
2237 "IV size is not compatible with the omp runtime");
2238 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2239 : "__kmpc_for_static_init_4u")
2240 : (IVSigned ? "__kmpc_for_static_init_8"
2241 : "__kmpc_for_static_init_8u");
2242 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2243 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2244 llvm::Type *TypeParams[] = {
2245 getIdentTyPointerTy(), // loc
2246 CGM.Int32Ty, // tid
2247 CGM.Int32Ty, // schedtype
2248 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2249 PtrTy, // p_lower
2250 PtrTy, // p_upper
2251 PtrTy, // p_stride
2252 ITy, // incr
2253 ITy // chunk
2254 };
2255 llvm::FunctionType *FnTy =
2256 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2257 return CGM.CreateRuntimeFunction(FnTy, Name);
2258}
2259
Alexander Musman92bdaab2015-03-12 13:37:50 +00002260llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2261 bool IVSigned) {
2262 assert((IVSize == 32 || IVSize == 64) &&
2263 "IV size is not compatible with the omp runtime");
2264 auto Name =
2265 IVSize == 32
2266 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2267 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2268 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2269 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2270 CGM.Int32Ty, // tid
2271 CGM.Int32Ty, // schedtype
2272 ITy, // lower
2273 ITy, // upper
2274 ITy, // stride
2275 ITy // chunk
2276 };
2277 llvm::FunctionType *FnTy =
2278 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2279 return CGM.CreateRuntimeFunction(FnTy, Name);
2280}
2281
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002282llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2283 bool IVSigned) {
2284 assert((IVSize == 32 || IVSize == 64) &&
2285 "IV size is not compatible with the omp runtime");
2286 auto Name =
2287 IVSize == 32
2288 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2289 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2290 llvm::Type *TypeParams[] = {
2291 getIdentTyPointerTy(), // loc
2292 CGM.Int32Ty, // tid
2293 };
2294 llvm::FunctionType *FnTy =
2295 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2296 return CGM.CreateRuntimeFunction(FnTy, Name);
2297}
2298
Alexander Musman92bdaab2015-03-12 13:37:50 +00002299llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2300 bool IVSigned) {
2301 assert((IVSize == 32 || IVSize == 64) &&
2302 "IV size is not compatible with the omp runtime");
2303 auto Name =
2304 IVSize == 32
2305 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2306 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2307 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2308 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2309 llvm::Type *TypeParams[] = {
2310 getIdentTyPointerTy(), // loc
2311 CGM.Int32Ty, // tid
2312 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2313 PtrTy, // p_lower
2314 PtrTy, // p_upper
2315 PtrTy // p_stride
2316 };
2317 llvm::FunctionType *FnTy =
2318 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2319 return CGM.CreateRuntimeFunction(FnTy, Name);
2320}
2321
Alexey Bataev97720002014-11-11 04:05:39 +00002322llvm::Constant *
2323CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002324 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2325 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002326 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002327 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002328 Twine(CGM.getMangledName(VD)) + ".cache.");
2329}
2330
John McCall7f416cc2015-09-08 08:05:57 +00002331Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2332 const VarDecl *VD,
2333 Address VDAddr,
2334 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002335 if (CGM.getLangOpts().OpenMPUseTLS &&
2336 CGM.getContext().getTargetInfo().isTLSSupported())
2337 return VDAddr;
2338
John McCall7f416cc2015-09-08 08:05:57 +00002339 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002340 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002341 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2342 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002343 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2344 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002345 return Address(CGF.EmitRuntimeCall(
2346 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2347 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002348}
2349
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002350void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002351 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002352 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2353 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2354 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002355 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2356 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002357 OMPLoc);
2358 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2359 // to register constructor/destructor for variable.
2360 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002361 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2362 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002363 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002364 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002365 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002366}
2367
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002368llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002369 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002370 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002371 if (CGM.getLangOpts().OpenMPUseTLS &&
2372 CGM.getContext().getTargetInfo().isTLSSupported())
2373 return nullptr;
2374
Alexey Bataev97720002014-11-11 04:05:39 +00002375 VD = VD->getDefinition(CGM.getContext());
2376 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2377 ThreadPrivateWithDefinition.insert(VD);
2378 QualType ASTTy = VD->getType();
2379
2380 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2381 auto Init = VD->getAnyInitializer();
2382 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2383 // Generate function that re-emits the declaration's initializer into the
2384 // threadprivate copy of the variable VD
2385 CodeGenFunction CtorCGF(CGM);
2386 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002387 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2388 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002389 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002390 Args.push_back(&Dst);
2391
John McCallc56a8b32016-03-11 04:30:31 +00002392 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2393 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002394 auto FTy = CGM.getTypes().GetFunctionType(FI);
2395 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002396 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002397 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002398 Args, Loc, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002399 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002400 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002401 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002402 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002403 Arg = CtorCGF.Builder.CreateElementBitCast(
2404 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002405 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2406 /*IsInitializer=*/true);
2407 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002408 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002409 CGM.getContext().VoidPtrTy, Dst.getLocation());
2410 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2411 CtorCGF.FinishFunction();
2412 Ctor = Fn;
2413 }
2414 if (VD->getType().isDestructedType() != QualType::DK_none) {
2415 // Generate function that emits destructor call for the threadprivate copy
2416 // of the variable VD
2417 CodeGenFunction DtorCGF(CGM);
2418 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002419 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2420 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002421 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002422 Args.push_back(&Dst);
2423
John McCallc56a8b32016-03-11 04:30:31 +00002424 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2425 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002426 auto FTy = CGM.getTypes().GetFunctionType(FI);
2427 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002428 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002429 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002430 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002431 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002432 // Create a scope with an artificial location for the body of this function.
2433 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002434 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2435 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002436 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2437 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002438 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2439 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2440 DtorCGF.FinishFunction();
2441 Dtor = Fn;
2442 }
2443 // Do not emit init function if it is not required.
2444 if (!Ctor && !Dtor)
2445 return nullptr;
2446
2447 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2448 auto CopyCtorTy =
2449 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2450 /*isVarArg=*/false)->getPointerTo();
2451 // Copying constructor for the threadprivate variable.
2452 // Must be NULL - reserved by runtime, but currently it requires that this
2453 // parameter is always NULL. Otherwise it fires assertion.
2454 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2455 if (Ctor == nullptr) {
2456 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2457 /*isVarArg=*/false)->getPointerTo();
2458 Ctor = llvm::Constant::getNullValue(CtorTy);
2459 }
2460 if (Dtor == nullptr) {
2461 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2462 /*isVarArg=*/false)->getPointerTo();
2463 Dtor = llvm::Constant::getNullValue(DtorTy);
2464 }
2465 if (!CGF) {
2466 auto InitFunctionTy =
2467 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2468 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002469 InitFunctionTy, ".__omp_threadprivate_init_.",
2470 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002471 CodeGenFunction InitCGF(CGM);
2472 FunctionArgList ArgList;
2473 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2474 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002475 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002476 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002477 InitCGF.FinishFunction();
2478 return InitFunction;
2479 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002480 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002481 }
2482 return nullptr;
2483}
2484
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002485Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2486 QualType VarType,
2487 StringRef Name) {
2488 llvm::Twine VarName(Name, ".artificial.");
2489 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2490 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2491 llvm::Value *Args[] = {
2492 emitUpdateLocation(CGF, SourceLocation()),
2493 getThreadID(CGF, SourceLocation()),
2494 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2495 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2496 /*IsSigned=*/false),
2497 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2498 return Address(
2499 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2500 CGF.EmitRuntimeCall(
2501 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2502 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2503 CGM.getPointerAlign());
2504}
2505
Alexey Bataev1d677132015-04-22 13:57:31 +00002506/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2507/// function. Here is the logic:
2508/// if (Cond) {
2509/// ThenGen();
2510/// } else {
2511/// ElseGen();
2512/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002513void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2514 const RegionCodeGenTy &ThenGen,
2515 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002516 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2517
2518 // If the condition constant folds and can be elided, try to avoid emitting
2519 // the condition and the dead arm of the if/else.
2520 bool CondConstant;
2521 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002522 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002523 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002524 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002525 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002526 return;
2527 }
2528
2529 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2530 // emit the conditional branch.
2531 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2532 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2533 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2534 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2535
2536 // Emit the 'then' code.
2537 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002538 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002539 CGF.EmitBranch(ContBlock);
2540 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002541 // There is no need to emit line number for unconditional branch.
2542 (void)ApplyDebugLocation::CreateEmpty(CGF);
2543 CGF.EmitBlock(ElseBlock);
2544 ElseGen(CGF);
2545 // There is no need to emit line number for unconditional branch.
2546 (void)ApplyDebugLocation::CreateEmpty(CGF);
2547 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002548 // Emit the continuation block for code after the if.
2549 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002550}
2551
Alexey Bataev1d677132015-04-22 13:57:31 +00002552void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2553 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002554 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002555 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002556 if (!CGF.HaveInsertPoint())
2557 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002558 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002559 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2560 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002561 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002562 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002563 llvm::Value *Args[] = {
2564 RTLoc,
2565 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002566 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002567 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2568 RealArgs.append(std::begin(Args), std::end(Args));
2569 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2570
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002571 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002572 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2573 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002574 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2575 PrePostActionTy &) {
2576 auto &RT = CGF.CGM.getOpenMPRuntime();
2577 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002578 // Build calls:
2579 // __kmpc_serialized_parallel(&Loc, GTid);
2580 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002581 CGF.EmitRuntimeCall(
2582 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002583
Alexey Bataev1d677132015-04-22 13:57:31 +00002584 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002585 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002586 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002587 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2588 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002589 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002590 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2591 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2592 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2593 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002594 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002595
Alexey Bataev1d677132015-04-22 13:57:31 +00002596 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002597 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002598 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002599 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2600 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002601 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002602 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002603 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002604 else {
2605 RegionCodeGenTy ThenRCG(ThenGen);
2606 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002607 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002608}
2609
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002610// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002611// thread-ID variable (it is passed in a first argument of the outlined function
2612// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2613// regular serial code region, get thread ID by calling kmp_int32
2614// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2615// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002616Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2617 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002618 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002619 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002620 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002621 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002622
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002623 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002624 auto Int32Ty =
2625 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2626 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2627 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002628 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002629
2630 return ThreadIDTemp;
2631}
2632
Alexey Bataev97720002014-11-11 04:05:39 +00002633llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002634CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002635 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002636 SmallString<256> Buffer;
2637 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002638 Out << Name;
2639 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002640 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2641 if (Elem.second) {
2642 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002643 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002644 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002645 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002646
David Blaikie13156b62014-11-19 03:06:06 +00002647 return Elem.second = new llvm::GlobalVariable(
2648 CGM.getModule(), Ty, /*IsConstant*/ false,
2649 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2650 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002651}
2652
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002653llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002654 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002655 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002656}
2657
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002658namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002659/// Common pre(post)-action for different OpenMP constructs.
2660class CommonActionTy final : public PrePostActionTy {
2661 llvm::Value *EnterCallee;
2662 ArrayRef<llvm::Value *> EnterArgs;
2663 llvm::Value *ExitCallee;
2664 ArrayRef<llvm::Value *> ExitArgs;
2665 bool Conditional;
2666 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002667
2668public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002669 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2670 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2671 bool Conditional = false)
2672 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2673 ExitArgs(ExitArgs), Conditional(Conditional) {}
2674 void Enter(CodeGenFunction &CGF) override {
2675 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2676 if (Conditional) {
2677 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2678 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2679 ContBlock = CGF.createBasicBlock("omp_if.end");
2680 // Generate the branch (If-stmt)
2681 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2682 CGF.EmitBlock(ThenBlock);
2683 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002684 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002685 void Done(CodeGenFunction &CGF) {
2686 // Emit the rest of blocks/branches
2687 CGF.EmitBranch(ContBlock);
2688 CGF.EmitBlock(ContBlock, true);
2689 }
2690 void Exit(CodeGenFunction &CGF) override {
2691 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002692 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002693};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002694} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002695
2696void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2697 StringRef CriticalName,
2698 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002699 SourceLocation Loc, const Expr *Hint) {
2700 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002701 // CriticalOpGen();
2702 // __kmpc_end_critical(ident_t *, gtid, Lock);
2703 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002704 if (!CGF.HaveInsertPoint())
2705 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002706 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2707 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002708 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2709 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002710 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002711 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2712 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2713 }
2714 CommonActionTy Action(
2715 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2716 : OMPRTL__kmpc_critical),
2717 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2718 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002719 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002720}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002721
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002722void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002723 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002724 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002725 if (!CGF.HaveInsertPoint())
2726 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002727 // if(__kmpc_master(ident_t *, gtid)) {
2728 // MasterOpGen();
2729 // __kmpc_end_master(ident_t *, gtid);
2730 // }
2731 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002732 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002733 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2734 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2735 /*Conditional=*/true);
2736 MasterOpGen.setAction(Action);
2737 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2738 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002739}
2740
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002741void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2742 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002743 if (!CGF.HaveInsertPoint())
2744 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002745 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2746 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002747 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002748 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002749 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002750 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2751 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002752}
2753
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002754void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2755 const RegionCodeGenTy &TaskgroupOpGen,
2756 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002757 if (!CGF.HaveInsertPoint())
2758 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002759 // __kmpc_taskgroup(ident_t *, gtid);
2760 // TaskgroupOpGen();
2761 // __kmpc_end_taskgroup(ident_t *, gtid);
2762 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002763 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2764 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2765 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2766 Args);
2767 TaskgroupOpGen.setAction(Action);
2768 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002769}
2770
John McCall7f416cc2015-09-08 08:05:57 +00002771/// Given an array of pointers to variables, project the address of a
2772/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002773static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2774 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002775 // Pull out the pointer to the variable.
2776 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002777 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002778 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2779
2780 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002781 Addr = CGF.Builder.CreateElementBitCast(
2782 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002783 return Addr;
2784}
2785
Alexey Bataeva63048e2015-03-23 06:18:07 +00002786static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002787 CodeGenModule &CGM, llvm::Type *ArgsType,
2788 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002789 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2790 SourceLocation Loc) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002791 auto &C = CGM.getContext();
2792 // void copy_func(void *LHSArg, void *RHSArg);
2793 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002794 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2795 ImplicitParamDecl::Other);
2796 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2797 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002798 Args.push_back(&LHSArg);
2799 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002800 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002801 auto *Fn = llvm::Function::Create(
2802 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2803 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002804 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002805 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002806 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002807 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002808 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002809 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2810 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2811 ArgsType), CGF.getPointerAlign());
2812 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2813 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2814 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002815 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2816 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2817 // ...
2818 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002819 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002820 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2821 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2822
2823 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2824 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2825
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002826 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2827 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002828 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002829 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002830 CGF.FinishFunction();
2831 return Fn;
2832}
2833
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002834void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002835 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002836 SourceLocation Loc,
2837 ArrayRef<const Expr *> CopyprivateVars,
2838 ArrayRef<const Expr *> SrcExprs,
2839 ArrayRef<const Expr *> DstExprs,
2840 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002841 if (!CGF.HaveInsertPoint())
2842 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002843 assert(CopyprivateVars.size() == SrcExprs.size() &&
2844 CopyprivateVars.size() == DstExprs.size() &&
2845 CopyprivateVars.size() == AssignmentOps.size());
2846 auto &C = CGM.getContext();
2847 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002848 // if(__kmpc_single(ident_t *, gtid)) {
2849 // SingleOpGen();
2850 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002851 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002852 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002853 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2854 // <copy_func>, did_it);
2855
John McCall7f416cc2015-09-08 08:05:57 +00002856 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002857 if (!CopyprivateVars.empty()) {
2858 // int32 did_it = 0;
2859 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2860 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002861 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002862 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002863 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002864 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002865 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2866 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2867 /*Conditional=*/true);
2868 SingleOpGen.setAction(Action);
2869 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2870 if (DidIt.isValid()) {
2871 // did_it = 1;
2872 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2873 }
2874 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002875 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2876 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002877 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002878 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2879 auto CopyprivateArrayTy =
2880 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2881 /*IndexTypeQuals=*/0);
2882 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002883 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002884 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2885 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002886 Address Elem = CGF.Builder.CreateConstArrayGEP(
2887 CopyprivateList, I, CGF.getPointerSize());
2888 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002889 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002890 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2891 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002892 }
2893 // Build function that copies private values from single region to all other
2894 // threads in the corresponding parallel region.
2895 auto *CpyFn = emitCopyprivateCopyFunction(
2896 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002897 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002898 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002899 Address CL =
2900 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2901 CGF.VoidPtrTy);
2902 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002903 llvm::Value *Args[] = {
2904 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2905 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002906 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002907 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002908 CpyFn, // void (*) (void *, void *) <copy_func>
2909 DidItVal // i32 did_it
2910 };
2911 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2912 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002913}
2914
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002915void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2916 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002917 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002918 if (!CGF.HaveInsertPoint())
2919 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002920 // __kmpc_ordered(ident_t *, gtid);
2921 // OrderedOpGen();
2922 // __kmpc_end_ordered(ident_t *, gtid);
2923 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002924 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002925 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002926 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2927 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2928 Args);
2929 OrderedOpGen.setAction(Action);
2930 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2931 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002932 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002933 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002934}
2935
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002936void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002937 OpenMPDirectiveKind Kind, bool EmitChecks,
2938 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002939 if (!CGF.HaveInsertPoint())
2940 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002941 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002942 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002943 unsigned Flags;
2944 if (Kind == OMPD_for)
2945 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2946 else if (Kind == OMPD_sections)
2947 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2948 else if (Kind == OMPD_single)
2949 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2950 else if (Kind == OMPD_barrier)
2951 Flags = OMP_IDENT_BARRIER_EXPL;
2952 else
2953 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002954 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2955 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002956 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2957 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002958 if (auto *OMPRegionInfo =
2959 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002960 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002961 auto *Result = CGF.EmitRuntimeCall(
2962 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002963 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002964 // if (__kmpc_cancel_barrier()) {
2965 // exit from construct;
2966 // }
2967 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2968 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2969 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2970 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2971 CGF.EmitBlock(ExitBB);
2972 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002973 auto CancelDestination =
2974 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002975 CGF.EmitBranchThroughCleanup(CancelDestination);
2976 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2977 }
2978 return;
2979 }
2980 }
2981 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002982}
2983
Alexander Musmanc6388682014-12-15 07:07:06 +00002984/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2985static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002986 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002987 switch (ScheduleKind) {
2988 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002989 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2990 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002991 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002992 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002993 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002994 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002995 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002996 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2997 case OMPC_SCHEDULE_auto:
2998 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002999 case OMPC_SCHEDULE_unknown:
3000 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003001 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003002 }
3003 llvm_unreachable("Unexpected runtime schedule");
3004}
3005
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003006/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3007static OpenMPSchedType
3008getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3009 // only static is allowed for dist_schedule
3010 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3011}
3012
Alexander Musmanc6388682014-12-15 07:07:06 +00003013bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3014 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003015 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003016 return Schedule == OMP_sch_static;
3017}
3018
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003019bool CGOpenMPRuntime::isStaticNonchunked(
3020 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3021 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3022 return Schedule == OMP_dist_sch_static;
3023}
3024
3025
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003026bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003027 auto Schedule =
3028 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003029 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3030 return Schedule != OMP_sch_static;
3031}
3032
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003033static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3034 OpenMPScheduleClauseModifier M1,
3035 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003036 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003037 switch (M1) {
3038 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003039 Modifier = OMP_sch_modifier_monotonic;
3040 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003041 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003042 Modifier = OMP_sch_modifier_nonmonotonic;
3043 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003044 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003045 if (Schedule == OMP_sch_static_chunked)
3046 Schedule = OMP_sch_static_balanced_chunked;
3047 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003048 case OMPC_SCHEDULE_MODIFIER_last:
3049 case OMPC_SCHEDULE_MODIFIER_unknown:
3050 break;
3051 }
3052 switch (M2) {
3053 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003054 Modifier = OMP_sch_modifier_monotonic;
3055 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003056 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003057 Modifier = OMP_sch_modifier_nonmonotonic;
3058 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003059 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003060 if (Schedule == OMP_sch_static_chunked)
3061 Schedule = OMP_sch_static_balanced_chunked;
3062 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003063 case OMPC_SCHEDULE_MODIFIER_last:
3064 case OMPC_SCHEDULE_MODIFIER_unknown:
3065 break;
3066 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003067 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003068}
3069
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003070void CGOpenMPRuntime::emitForDispatchInit(
3071 CodeGenFunction &CGF, SourceLocation Loc,
3072 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3073 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003074 if (!CGF.HaveInsertPoint())
3075 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003076 OpenMPSchedType Schedule = getRuntimeSchedule(
3077 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003078 assert(Ordered ||
3079 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003080 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3081 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003082 // Call __kmpc_dispatch_init(
3083 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3084 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3085 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003086
John McCall7f416cc2015-09-08 08:05:57 +00003087 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003088 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3089 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003090 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003091 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3092 CGF.Builder.getInt32(addMonoNonMonoModifier(
3093 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003094 DispatchValues.LB, // Lower
3095 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003096 CGF.Builder.getIntN(IVSize, 1), // Stride
3097 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003098 };
3099 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3100}
3101
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003102static void emitForStaticInitCall(
3103 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3104 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3105 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003106 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003107 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003108 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003109
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003110 assert(!Values.Ordered);
3111 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3112 Schedule == OMP_sch_static_balanced_chunked ||
3113 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3114 Schedule == OMP_dist_sch_static ||
3115 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003116
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003117 // Call __kmpc_for_static_init(
3118 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3119 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3120 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3121 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3122 llvm::Value *Chunk = Values.Chunk;
3123 if (Chunk == nullptr) {
3124 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3125 Schedule == OMP_dist_sch_static) &&
3126 "expected static non-chunked schedule");
3127 // If the Chunk was not specified in the clause - use default value 1.
3128 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3129 } else {
3130 assert((Schedule == OMP_sch_static_chunked ||
3131 Schedule == OMP_sch_static_balanced_chunked ||
3132 Schedule == OMP_ord_static_chunked ||
3133 Schedule == OMP_dist_sch_static_chunked) &&
3134 "expected static chunked schedule");
3135 }
3136 llvm::Value *Args[] = {
3137 UpdateLocation,
3138 ThreadId,
3139 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3140 M2)), // Schedule type
3141 Values.IL.getPointer(), // &isLastIter
3142 Values.LB.getPointer(), // &LB
3143 Values.UB.getPointer(), // &UB
3144 Values.ST.getPointer(), // &Stride
3145 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3146 Chunk // Chunk
3147 };
3148 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003149}
3150
John McCall7f416cc2015-09-08 08:05:57 +00003151void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3152 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003153 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003154 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003155 const StaticRTInput &Values) {
3156 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3157 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3158 assert(isOpenMPWorksharingDirective(DKind) &&
3159 "Expected loop-based or sections-based directive.");
3160 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3161 isOpenMPLoopDirective(DKind)
3162 ? OMP_IDENT_WORK_LOOP
3163 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003164 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003165 auto *StaticInitFunction =
3166 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003167 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003168 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003169}
John McCall7f416cc2015-09-08 08:05:57 +00003170
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003171void CGOpenMPRuntime::emitDistributeStaticInit(
3172 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003173 OpenMPDistScheduleClauseKind SchedKind,
3174 const CGOpenMPRuntime::StaticRTInput &Values) {
3175 OpenMPSchedType ScheduleNum =
3176 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3177 auto *UpdatedLocation =
3178 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003179 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003180 auto *StaticInitFunction =
3181 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003182 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3183 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003184 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003185}
3186
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003187void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003188 SourceLocation Loc,
3189 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003190 if (!CGF.HaveInsertPoint())
3191 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003192 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003193 llvm::Value *Args[] = {
3194 emitUpdateLocation(CGF, Loc,
3195 isOpenMPDistributeDirective(DKind)
3196 ? OMP_IDENT_WORK_DISTRIBUTE
3197 : isOpenMPLoopDirective(DKind)
3198 ? OMP_IDENT_WORK_LOOP
3199 : OMP_IDENT_WORK_SECTIONS),
3200 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003201 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3202 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003203}
3204
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003205void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3206 SourceLocation Loc,
3207 unsigned IVSize,
3208 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003209 if (!CGF.HaveInsertPoint())
3210 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003211 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003212 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003213 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3214}
3215
Alexander Musman92bdaab2015-03-12 13:37:50 +00003216llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3217 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003218 bool IVSigned, Address IL,
3219 Address LB, Address UB,
3220 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003221 // Call __kmpc_dispatch_next(
3222 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3223 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3224 // kmp_int[32|64] *p_stride);
3225 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003226 emitUpdateLocation(CGF, Loc),
3227 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003228 IL.getPointer(), // &isLastIter
3229 LB.getPointer(), // &Lower
3230 UB.getPointer(), // &Upper
3231 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003232 };
3233 llvm::Value *Call =
3234 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3235 return CGF.EmitScalarConversion(
3236 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003237 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003238}
3239
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003240void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3241 llvm::Value *NumThreads,
3242 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003243 if (!CGF.HaveInsertPoint())
3244 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003245 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3246 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003247 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003248 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003249 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3250 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003251}
3252
Alexey Bataev7f210c62015-06-18 13:40:03 +00003253void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3254 OpenMPProcBindClauseKind ProcBind,
3255 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003256 if (!CGF.HaveInsertPoint())
3257 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003258 // Constants for proc bind value accepted by the runtime.
3259 enum ProcBindTy {
3260 ProcBindFalse = 0,
3261 ProcBindTrue,
3262 ProcBindMaster,
3263 ProcBindClose,
3264 ProcBindSpread,
3265 ProcBindIntel,
3266 ProcBindDefault
3267 } RuntimeProcBind;
3268 switch (ProcBind) {
3269 case OMPC_PROC_BIND_master:
3270 RuntimeProcBind = ProcBindMaster;
3271 break;
3272 case OMPC_PROC_BIND_close:
3273 RuntimeProcBind = ProcBindClose;
3274 break;
3275 case OMPC_PROC_BIND_spread:
3276 RuntimeProcBind = ProcBindSpread;
3277 break;
3278 case OMPC_PROC_BIND_unknown:
3279 llvm_unreachable("Unsupported proc_bind value.");
3280 }
3281 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3282 llvm::Value *Args[] = {
3283 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3284 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3285 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3286}
3287
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003288void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3289 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003290 if (!CGF.HaveInsertPoint())
3291 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003292 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003293 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3294 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003295}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003296
Alexey Bataev62b63b12015-03-10 07:28:44 +00003297namespace {
3298/// \brief Indexes of fields for type kmp_task_t.
3299enum KmpTaskTFields {
3300 /// \brief List of shared variables.
3301 KmpTaskTShareds,
3302 /// \brief Task routine.
3303 KmpTaskTRoutine,
3304 /// \brief Partition id for the untied tasks.
3305 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003306 /// Function with call of destructors for private variables.
3307 Data1,
3308 /// Task priority.
3309 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003310 /// (Taskloops only) Lower bound.
3311 KmpTaskTLowerBound,
3312 /// (Taskloops only) Upper bound.
3313 KmpTaskTUpperBound,
3314 /// (Taskloops only) Stride.
3315 KmpTaskTStride,
3316 /// (Taskloops only) Is last iteration flag.
3317 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003318 /// (Taskloops only) Reduction data.
3319 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003320};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003321} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003322
Samuel Antaoee8fb302016-01-06 13:42:12 +00003323bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3324 // FIXME: Add other entries type when they become supported.
3325 return OffloadEntriesTargetRegion.empty();
3326}
3327
3328/// \brief Initialize target region entry.
3329void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3330 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3331 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003332 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003333 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3334 "only required for the device "
3335 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003336 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003337 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3338 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003339 ++OffloadingEntriesNum;
3340}
3341
3342void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3343 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3344 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003345 llvm::Constant *Addr, llvm::Constant *ID,
3346 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003347 // If we are emitting code for a target, the entry is already initialized,
3348 // only has to be registered.
3349 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003350 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003351 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003352 auto &Entry =
3353 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003354 assert(Entry.isValid() && "Entry not initialized!");
3355 Entry.setAddress(Addr);
3356 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003357 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003358 return;
3359 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003360 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003361 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003362 }
3363}
3364
3365bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003366 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3367 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003368 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3369 if (PerDevice == OffloadEntriesTargetRegion.end())
3370 return false;
3371 auto PerFile = PerDevice->second.find(FileID);
3372 if (PerFile == PerDevice->second.end())
3373 return false;
3374 auto PerParentName = PerFile->second.find(ParentName);
3375 if (PerParentName == PerFile->second.end())
3376 return false;
3377 auto PerLine = PerParentName->second.find(LineNum);
3378 if (PerLine == PerParentName->second.end())
3379 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003380 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003381 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003382 return false;
3383 return true;
3384}
3385
3386void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3387 const OffloadTargetRegionEntryInfoActTy &Action) {
3388 // Scan all target region entries and perform the provided action.
3389 for (auto &D : OffloadEntriesTargetRegion)
3390 for (auto &F : D.second)
3391 for (auto &P : F.second)
3392 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003393 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003394}
3395
3396/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3397/// \a Codegen. This is used to emit the two functions that register and
3398/// unregister the descriptor of the current compilation unit.
3399static llvm::Function *
3400createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3401 const RegionCodeGenTy &Codegen) {
3402 auto &C = CGM.getContext();
3403 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003404 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003405 Args.push_back(&DummyPtr);
3406
3407 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003408 // Disable debug info for global (de-)initializer because they are not part of
3409 // some particular construct.
3410 CGF.disableDebugInfo();
John McCallc56a8b32016-03-11 04:30:31 +00003411 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003412 auto FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003413 auto *Fn = CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI);
3414 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003415 Codegen(CGF);
3416 CGF.FinishFunction();
3417 return Fn;
3418}
3419
3420llvm::Function *
3421CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003422 // If we don't have entries or if we are emitting code for the device, we
3423 // don't need to do anything.
3424 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3425 return nullptr;
3426
3427 auto &M = CGM.getModule();
3428 auto &C = CGM.getContext();
3429
3430 // Get list of devices we care about
3431 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3432
3433 // We should be creating an offloading descriptor only if there are devices
3434 // specified.
3435 assert(!Devices.empty() && "No OpenMP offloading devices??");
3436
3437 // Create the external variables that will point to the begin and end of the
3438 // host entries section. These will be defined by the linker.
3439 auto *OffloadEntryTy =
3440 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3441 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3442 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003443 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003444 ".omp_offloading.entries_begin");
3445 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3446 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003447 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003448 ".omp_offloading.entries_end");
3449
3450 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451 auto *DeviceImageTy = cast<llvm::StructType>(
3452 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003453 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003454 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003455
3456 for (unsigned i = 0; i < Devices.size(); ++i) {
3457 StringRef T = Devices[i].getTriple();
3458 auto *ImgBegin = new llvm::GlobalVariable(
3459 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003460 /*Initializer=*/nullptr,
3461 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003462 auto *ImgEnd = new llvm::GlobalVariable(
3463 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003464 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003465
John McCall6c9f1fdb2016-11-19 08:17:24 +00003466 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3467 Dev.add(ImgBegin);
3468 Dev.add(ImgEnd);
3469 Dev.add(HostEntriesBegin);
3470 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003471 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003472 }
3473
3474 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003475 llvm::GlobalVariable *DeviceImages =
3476 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3477 CGM.getPointerAlign(),
3478 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003479 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003480
3481 // This is a Zero array to be used in the creation of the constant expressions
3482 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3483 llvm::Constant::getNullValue(CGM.Int32Ty)};
3484
3485 // Create the target region descriptor.
3486 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3487 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003488 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003489 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3490 DescInit.addInt(CGM.Int32Ty, Devices.size());
3491 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3492 DeviceImages,
3493 Index));
3494 DescInit.add(HostEntriesBegin);
3495 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003496
John McCall6c9f1fdb2016-11-19 08:17:24 +00003497 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3498 CGM.getPointerAlign(),
3499 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003500
3501 // Emit code to register or unregister the descriptor at execution
3502 // startup or closing, respectively.
3503
3504 // Create a variable to drive the registration and unregistration of the
3505 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3506 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3507 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003508 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003509
3510 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003511 CGM, ".omp_offloading.descriptor_unreg",
3512 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003513 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3514 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003515 });
3516 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003517 CGM, ".omp_offloading.descriptor_reg",
3518 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003519 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3520 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003521 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3522 });
George Rokos29d0f002017-05-27 03:03:13 +00003523 if (CGM.supportsCOMDAT()) {
3524 // It is sufficient to call registration function only once, so create a
3525 // COMDAT group for registration/unregistration functions and associated
3526 // data. That would reduce startup time and code size. Registration
3527 // function serves as a COMDAT group key.
3528 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3529 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3530 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3531 RegFn->setComdat(ComdatKey);
3532 UnRegFn->setComdat(ComdatKey);
3533 DeviceImages->setComdat(ComdatKey);
3534 Desc->setComdat(ComdatKey);
3535 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003536 return RegFn;
3537}
3538
Samuel Antao2de62b02016-02-13 23:35:10 +00003539void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003540 llvm::Constant *Addr, uint64_t Size,
3541 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003542 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003543 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3544 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3545 llvm::LLVMContext &C = CGM.getModule().getContext();
3546 llvm::Module &M = CGM.getModule();
3547
3548 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003549 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003550
3551 // Create constant string with the name.
3552 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3553
3554 llvm::GlobalVariable *Str =
3555 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3556 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3557 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003558 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003559 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3560
John McCall6c9f1fdb2016-11-19 08:17:24 +00003561 // We can't have any padding between symbols, so we need to have 1-byte
3562 // alignment.
3563 auto Align = CharUnits::fromQuantity(1);
3564
Samuel Antaoee8fb302016-01-06 13:42:12 +00003565 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003566 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003567 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3568 EntryInit.add(AddrPtr);
3569 EntryInit.add(StrPtr);
3570 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003571 EntryInit.addInt(CGM.Int32Ty, Flags);
3572 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003573 llvm::GlobalVariable *Entry =
3574 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3575 Align,
3576 /*constant*/ true,
3577 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003578
3579 // The entry has to be created in the section the linker expects it to be.
3580 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003581}
3582
3583void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3584 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003585 // can easily figure out what to emit. The produced metadata looks like
3586 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003587 //
3588 // !omp_offload.info = !{!1, ...}
3589 //
3590 // Right now we only generate metadata for function that contain target
3591 // regions.
3592
3593 // If we do not have entries, we dont need to do anything.
3594 if (OffloadEntriesInfoManager.empty())
3595 return;
3596
3597 llvm::Module &M = CGM.getModule();
3598 llvm::LLVMContext &C = M.getContext();
3599 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3600 OrderedEntries(OffloadEntriesInfoManager.size());
3601
3602 // Create the offloading info metadata node.
3603 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3604
Simon Pilgrim2c518802017-03-30 14:13:19 +00003605 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003606 auto getMDInt = [&](unsigned v) {
3607 return llvm::ConstantAsMetadata::get(
3608 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3609 };
3610
3611 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3612
3613 // Create function that emits metadata for each target region entry;
3614 auto &&TargetRegionMetadataEmitter = [&](
3615 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003616 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3617 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3618 // Generate metadata for target regions. Each entry of this metadata
3619 // contains:
3620 // - Entry 0 -> Kind of this type of metadata (0).
3621 // - Entry 1 -> Device ID of the file where the entry was identified.
3622 // - Entry 2 -> File ID of the file where the entry was identified.
3623 // - Entry 3 -> Mangled name of the function where the entry was identified.
3624 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003625 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003626 // The first element of the metadata node is the kind.
3627 Ops.push_back(getMDInt(E.getKind()));
3628 Ops.push_back(getMDInt(DeviceID));
3629 Ops.push_back(getMDInt(FileID));
3630 Ops.push_back(getMDString(ParentName));
3631 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003632 Ops.push_back(getMDInt(E.getOrder()));
3633
3634 // Save this entry in the right position of the ordered entries array.
3635 OrderedEntries[E.getOrder()] = &E;
3636
3637 // Add metadata to the named metadata node.
3638 MD->addOperand(llvm::MDNode::get(C, Ops));
3639 };
3640
3641 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3642 TargetRegionMetadataEmitter);
3643
3644 for (auto *E : OrderedEntries) {
3645 assert(E && "All ordered entries must exist!");
3646 if (auto *CE =
3647 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3648 E)) {
3649 assert(CE->getID() && CE->getAddress() &&
3650 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003651 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003652 } else
3653 llvm_unreachable("Unsupported entry kind.");
3654 }
3655}
3656
3657/// \brief Loads all the offload entries information from the host IR
3658/// metadata.
3659void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3660 // If we are in target mode, load the metadata from the host IR. This code has
3661 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3662
3663 if (!CGM.getLangOpts().OpenMPIsDevice)
3664 return;
3665
3666 if (CGM.getLangOpts().OMPHostIRFile.empty())
3667 return;
3668
3669 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3670 if (Buf.getError())
3671 return;
3672
3673 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003674 auto ME = expectedToErrorOrAndEmitErrors(
3675 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003676
3677 if (ME.getError())
3678 return;
3679
3680 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3681 if (!MD)
3682 return;
3683
3684 for (auto I : MD->operands()) {
3685 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3686
3687 auto getMDInt = [&](unsigned Idx) {
3688 llvm::ConstantAsMetadata *V =
3689 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3690 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3691 };
3692
3693 auto getMDString = [&](unsigned Idx) {
3694 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3695 return V->getString();
3696 };
3697
3698 switch (getMDInt(0)) {
3699 default:
3700 llvm_unreachable("Unexpected metadata!");
3701 break;
3702 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3703 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3704 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3705 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3706 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003707 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003708 break;
3709 }
3710 }
3711}
3712
Alexey Bataev62b63b12015-03-10 07:28:44 +00003713void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3714 if (!KmpRoutineEntryPtrTy) {
3715 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3716 auto &C = CGM.getContext();
3717 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3718 FunctionProtoType::ExtProtoInfo EPI;
3719 KmpRoutineEntryPtrQTy = C.getPointerType(
3720 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3721 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3722 }
3723}
3724
Alexey Bataevc71a4092015-09-11 10:29:41 +00003725static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3726 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003727 auto *Field = FieldDecl::Create(
3728 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3729 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3730 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3731 Field->setAccess(AS_public);
3732 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003733 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003734}
3735
Samuel Antaoee8fb302016-01-06 13:42:12 +00003736QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3737
3738 // Make sure the type of the entry is already created. This is the type we
3739 // have to create:
3740 // struct __tgt_offload_entry{
3741 // void *addr; // Pointer to the offload entry info.
3742 // // (function or global)
3743 // char *name; // Name of the function or global.
3744 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003745 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3746 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003747 // };
3748 if (TgtOffloadEntryQTy.isNull()) {
3749 ASTContext &C = CGM.getContext();
3750 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3751 RD->startDefinition();
3752 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3753 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3754 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003755 addFieldToRecordDecl(
3756 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3757 addFieldToRecordDecl(
3758 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003759 RD->completeDefinition();
3760 TgtOffloadEntryQTy = C.getRecordType(RD);
3761 }
3762 return TgtOffloadEntryQTy;
3763}
3764
3765QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3766 // These are the types we need to build:
3767 // struct __tgt_device_image{
3768 // void *ImageStart; // Pointer to the target code start.
3769 // void *ImageEnd; // Pointer to the target code end.
3770 // // We also add the host entries to the device image, as it may be useful
3771 // // for the target runtime to have access to that information.
3772 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3773 // // the entries.
3774 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3775 // // entries (non inclusive).
3776 // };
3777 if (TgtDeviceImageQTy.isNull()) {
3778 ASTContext &C = CGM.getContext();
3779 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3780 RD->startDefinition();
3781 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3782 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3783 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3784 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3785 RD->completeDefinition();
3786 TgtDeviceImageQTy = C.getRecordType(RD);
3787 }
3788 return TgtDeviceImageQTy;
3789}
3790
3791QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3792 // struct __tgt_bin_desc{
3793 // int32_t NumDevices; // Number of devices supported.
3794 // __tgt_device_image *DeviceImages; // Arrays of device images
3795 // // (one per device).
3796 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3797 // // entries.
3798 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3799 // // entries (non inclusive).
3800 // };
3801 if (TgtBinaryDescriptorQTy.isNull()) {
3802 ASTContext &C = CGM.getContext();
3803 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3804 RD->startDefinition();
3805 addFieldToRecordDecl(
3806 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3807 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3808 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3809 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3810 RD->completeDefinition();
3811 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3812 }
3813 return TgtBinaryDescriptorQTy;
3814}
3815
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003816namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003817struct PrivateHelpersTy {
3818 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3819 const VarDecl *PrivateElemInit)
3820 : Original(Original), PrivateCopy(PrivateCopy),
3821 PrivateElemInit(PrivateElemInit) {}
3822 const VarDecl *Original;
3823 const VarDecl *PrivateCopy;
3824 const VarDecl *PrivateElemInit;
3825};
3826typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003827} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003828
Alexey Bataev9e034042015-05-05 04:05:12 +00003829static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003830createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003831 if (!Privates.empty()) {
3832 auto &C = CGM.getContext();
3833 // Build struct .kmp_privates_t. {
3834 // /* private vars */
3835 // };
3836 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3837 RD->startDefinition();
3838 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003839 auto *VD = Pair.second.Original;
3840 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003841 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003842 auto *FD = addFieldToRecordDecl(C, RD, Type);
3843 if (VD->hasAttrs()) {
3844 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3845 E(VD->getAttrs().end());
3846 I != E; ++I)
3847 FD->addAttr(*I);
3848 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003849 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003850 RD->completeDefinition();
3851 return RD;
3852 }
3853 return nullptr;
3854}
3855
Alexey Bataev9e034042015-05-05 04:05:12 +00003856static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003857createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3858 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003859 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003860 auto &C = CGM.getContext();
3861 // Build struct kmp_task_t {
3862 // void * shareds;
3863 // kmp_routine_entry_t routine;
3864 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003865 // kmp_cmplrdata_t data1;
3866 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003867 // For taskloops additional fields:
3868 // kmp_uint64 lb;
3869 // kmp_uint64 ub;
3870 // kmp_int64 st;
3871 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003872 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003873 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003874 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3875 UD->startDefinition();
3876 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3877 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3878 UD->completeDefinition();
3879 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003880 auto *RD = C.buildImplicitRecord("kmp_task_t");
3881 RD->startDefinition();
3882 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3883 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3884 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003885 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3886 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003887 if (isOpenMPTaskLoopDirective(Kind)) {
3888 QualType KmpUInt64Ty =
3889 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3890 QualType KmpInt64Ty =
3891 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3892 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3893 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3894 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3895 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003896 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003897 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003898 RD->completeDefinition();
3899 return RD;
3900}
3901
3902static RecordDecl *
3903createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003904 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003905 auto &C = CGM.getContext();
3906 // Build struct kmp_task_t_with_privates {
3907 // kmp_task_t task_data;
3908 // .kmp_privates_t. privates;
3909 // };
3910 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3911 RD->startDefinition();
3912 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003913 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3914 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3915 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003916 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003917 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003918}
3919
3920/// \brief Emit a proxy function which accepts kmp_task_t as the second
3921/// argument.
3922/// \code
3923/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003924/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003925/// For taskloops:
3926/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003927/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003928/// return 0;
3929/// }
3930/// \endcode
3931static llvm::Value *
3932emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003933 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3934 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003935 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003936 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3937 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003938 auto &C = CGM.getContext();
3939 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003940 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3941 ImplicitParamDecl::Other);
3942 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3943 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3944 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003945 Args.push_back(&GtidArg);
3946 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003947 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003948 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003949 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3950 auto *TaskEntry =
3951 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3952 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003953 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003954 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003955 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
3956 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003957
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003958 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003959 // tt,
3960 // For taskloops:
3961 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3962 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003963 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003964 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003965 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3966 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3967 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003968 auto *KmpTaskTWithPrivatesQTyRD =
3969 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003970 LValue Base =
3971 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003972 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3973 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3974 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003975 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003976
3977 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3978 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003979 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003980 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003981 CGF.ConvertTypeForMem(SharedsPtrTy));
3982
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003983 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3984 llvm::Value *PrivatesParam;
3985 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3986 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3987 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003988 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003989 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003990 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003991
Alexey Bataev7292c292016-04-25 12:22:29 +00003992 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3993 TaskPrivatesMap,
3994 CGF.Builder
3995 .CreatePointerBitCastOrAddrSpaceCast(
3996 TDBase.getAddress(), CGF.VoidPtrTy)
3997 .getPointer()};
3998 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3999 std::end(CommonArgs));
4000 if (isOpenMPTaskLoopDirective(Kind)) {
4001 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
4002 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4003 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
4004 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4005 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4006 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
4007 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4008 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
4009 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
4010 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4011 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
4012 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004013 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4014 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
4015 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00004016 CallArgs.push_back(LBParam);
4017 CallArgs.push_back(UBParam);
4018 CallArgs.push_back(StParam);
4019 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004020 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004021 }
4022 CallArgs.push_back(SharedsParam);
4023
Alexey Bataev3c595a62017-08-14 15:01:03 +00004024 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4025 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004026 CGF.EmitStoreThroughLValue(
4027 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00004028 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004029 CGF.FinishFunction();
4030 return TaskEntry;
4031}
4032
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004033static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4034 SourceLocation Loc,
4035 QualType KmpInt32Ty,
4036 QualType KmpTaskTWithPrivatesPtrQTy,
4037 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00004038 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004039 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004040 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4041 ImplicitParamDecl::Other);
4042 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4043 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4044 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004045 Args.push_back(&GtidArg);
4046 Args.push_back(&TaskTypeArg);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004047 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004048 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004049 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
4050 auto *DestructorFn =
4051 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4052 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004053 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
4054 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004055 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004056 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004057 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004058
Alexey Bataev31300ed2016-02-04 11:27:03 +00004059 LValue Base = CGF.EmitLoadOfPointerLValue(
4060 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4061 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004062 auto *KmpTaskTWithPrivatesQTyRD =
4063 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4064 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004065 Base = CGF.EmitLValueForField(Base, *FI);
4066 for (auto *Field :
4067 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4068 if (auto DtorKind = Field->getType().isDestructedType()) {
4069 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
4070 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4071 }
4072 }
4073 CGF.FinishFunction();
4074 return DestructorFn;
4075}
4076
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004077/// \brief Emit a privates mapping function for correct handling of private and
4078/// firstprivate variables.
4079/// \code
4080/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4081/// **noalias priv1,..., <tyn> **noalias privn) {
4082/// *priv1 = &.privates.priv1;
4083/// ...;
4084/// *privn = &.privates.privn;
4085/// }
4086/// \endcode
4087static llvm::Value *
4088emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004089 ArrayRef<const Expr *> PrivateVars,
4090 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004091 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004092 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004093 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004094 auto &C = CGM.getContext();
4095 FunctionArgList Args;
4096 ImplicitParamDecl TaskPrivatesArg(
4097 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004098 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4099 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004100 Args.push_back(&TaskPrivatesArg);
4101 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4102 unsigned Counter = 1;
4103 for (auto *E: PrivateVars) {
4104 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004105 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4106 C.getPointerType(C.getPointerType(E->getType()))
4107 .withConst()
4108 .withRestrict(),
4109 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004110 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4111 PrivateVarsPos[VD] = Counter;
4112 ++Counter;
4113 }
4114 for (auto *E : FirstprivateVars) {
4115 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004116 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4117 C.getPointerType(C.getPointerType(E->getType()))
4118 .withConst()
4119 .withRestrict(),
4120 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004121 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4122 PrivateVarsPos[VD] = Counter;
4123 ++Counter;
4124 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004125 for (auto *E: LastprivateVars) {
4126 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004127 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4128 C.getPointerType(C.getPointerType(E->getType()))
4129 .withConst()
4130 .withRestrict(),
4131 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004132 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4133 PrivateVarsPos[VD] = Counter;
4134 ++Counter;
4135 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004136 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004137 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004138 auto *TaskPrivatesMapTy =
4139 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4140 auto *TaskPrivatesMap = llvm::Function::Create(
4141 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4142 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004143 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4144 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004145 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004146 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004147 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004148 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004149 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004150 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004151
4152 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004153 LValue Base = CGF.EmitLoadOfPointerLValue(
4154 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4155 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004156 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4157 Counter = 0;
4158 for (auto *Field : PrivatesQTyRD->fields()) {
4159 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4160 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004161 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004162 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4163 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004164 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004165 ++Counter;
4166 }
4167 CGF.FinishFunction();
4168 return TaskPrivatesMap;
4169}
4170
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004171static bool stable_sort_comparator(const PrivateDataTy P1,
4172 const PrivateDataTy P2) {
4173 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004174}
4175
Alexey Bataevf93095a2016-05-05 08:46:22 +00004176/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004177static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004178 const OMPExecutableDirective &D,
4179 Address KmpTaskSharedsPtr, LValue TDBase,
4180 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4181 QualType SharedsTy, QualType SharedsPtrTy,
4182 const OMPTaskDataTy &Data,
4183 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4184 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004185 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4186 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4187 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004188 bool IsTargetTask =
4189 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4190 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4191 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4192 // PointersArray and SizesArray. The original variables for these arrays are
4193 // not captured and we get their addresses explicitly.
4194 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
4195 (IsTargetTask && Data.FirstprivateVars.size() > 3)) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004196 SrcBase = CGF.MakeAddrLValue(
4197 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4198 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4199 SharedsTy);
4200 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004201 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4202 ? OMPD_taskloop
4203 : OMPD_task;
4204 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(*D.getCapturedStmt(Kind));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004205 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4206 for (auto &&Pair : Privates) {
4207 auto *VD = Pair.second.PrivateCopy;
4208 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004209 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4210 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004211 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004212 if (auto *Elem = Pair.second.PrivateElemInit) {
4213 auto *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004214 // Check if the variable is the target-based BasePointersArray,
4215 // PointersArray or SizesArray.
4216 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004217 QualType Type = OriginalVD->getType();
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004218 if (IsTargetTask && isa<ImplicitParamDecl>(OriginalVD) &&
4219 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4220 cast<CapturedDecl>(OriginalVD->getDeclContext())->getNumParams() ==
4221 0 &&
4222 isa<TranslationUnitDecl>(
4223 cast<CapturedDecl>(OriginalVD->getDeclContext())
4224 ->getDeclContext())) {
4225 SharedRefLValue =
4226 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4227 } else {
4228 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4229 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4230 SharedRefLValue = CGF.MakeAddrLValue(
4231 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4232 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4233 SharedRefLValue.getTBAAInfo());
4234 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004235 if (Type->isArrayType()) {
4236 // Initialize firstprivate array.
4237 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4238 // Perform simple memcpy.
4239 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4240 SharedRefLValue.getAddress(), Type);
4241 } else {
4242 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004243 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004244 CGF.EmitOMPAggregateAssign(
4245 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4246 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4247 Address SrcElement) {
4248 // Clean up any temporaries needed by the initialization.
4249 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4250 InitScope.addPrivate(
4251 Elem, [SrcElement]() -> Address { return SrcElement; });
4252 (void)InitScope.Privatize();
4253 // Emit initialization for single element.
4254 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4255 CGF, &CapturesInfo);
4256 CGF.EmitAnyExprToMem(Init, DestElement,
4257 Init->getType().getQualifiers(),
4258 /*IsInitializer=*/false);
4259 });
4260 }
4261 } else {
4262 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4263 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4264 return SharedRefLValue.getAddress();
4265 });
4266 (void)InitScope.Privatize();
4267 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4268 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4269 /*capturedByInit=*/false);
4270 }
4271 } else
4272 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4273 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004274 ++FI;
4275 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004276}
4277
4278/// Check if duplication function is required for taskloops.
4279static bool checkInitIsRequired(CodeGenFunction &CGF,
4280 ArrayRef<PrivateDataTy> Privates) {
4281 bool InitRequired = false;
4282 for (auto &&Pair : Privates) {
4283 auto *VD = Pair.second.PrivateCopy;
4284 auto *Init = VD->getAnyInitializer();
4285 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4286 !CGF.isTrivialInitializer(Init));
4287 }
4288 return InitRequired;
4289}
4290
4291
4292/// Emit task_dup function (for initialization of
4293/// private/firstprivate/lastprivate vars and last_iter flag)
4294/// \code
4295/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4296/// lastpriv) {
4297/// // setup lastprivate flag
4298/// task_dst->last = lastpriv;
4299/// // could be constructor calls here...
4300/// }
4301/// \endcode
4302static llvm::Value *
4303emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4304 const OMPExecutableDirective &D,
4305 QualType KmpTaskTWithPrivatesPtrQTy,
4306 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4307 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4308 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4309 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4310 auto &C = CGM.getContext();
4311 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004312 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4313 KmpTaskTWithPrivatesPtrQTy,
4314 ImplicitParamDecl::Other);
4315 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4316 KmpTaskTWithPrivatesPtrQTy,
4317 ImplicitParamDecl::Other);
4318 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4319 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004320 Args.push_back(&DstArg);
4321 Args.push_back(&SrcArg);
4322 Args.push_back(&LastprivArg);
4323 auto &TaskDupFnInfo =
4324 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4325 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4326 auto *TaskDup =
4327 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4328 ".omp_task_dup.", &CGM.getModule());
4329 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4330 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004331 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4332 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004333
4334 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4335 CGF.GetAddrOfLocalVar(&DstArg),
4336 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4337 // task_dst->liter = lastpriv;
4338 if (WithLastIter) {
4339 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4340 LValue Base = CGF.EmitLValueForField(
4341 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4342 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4343 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4344 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4345 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4346 }
4347
4348 // Emit initial values for private copies (if any).
4349 assert(!Privates.empty());
4350 Address KmpTaskSharedsPtr = Address::invalid();
4351 if (!Data.FirstprivateVars.empty()) {
4352 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4353 CGF.GetAddrOfLocalVar(&SrcArg),
4354 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4355 LValue Base = CGF.EmitLValueForField(
4356 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4357 KmpTaskSharedsPtr = Address(
4358 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4359 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4360 KmpTaskTShareds)),
4361 Loc),
4362 CGF.getNaturalTypeAlignment(SharedsTy));
4363 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004364 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4365 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004366 CGF.FinishFunction();
4367 return TaskDup;
4368}
4369
Alexey Bataev8a831592016-05-10 10:36:51 +00004370/// Checks if destructor function is required to be generated.
4371/// \return true if cleanups are required, false otherwise.
4372static bool
4373checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4374 bool NeedsCleanup = false;
4375 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4376 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4377 for (auto *FD : PrivateRD->fields()) {
4378 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4379 if (NeedsCleanup)
4380 break;
4381 }
4382 return NeedsCleanup;
4383}
4384
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004385CGOpenMPRuntime::TaskResultTy
4386CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4387 const OMPExecutableDirective &D,
4388 llvm::Value *TaskFunction, QualType SharedsTy,
4389 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004390 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004391 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004392 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004393 auto I = Data.PrivateCopies.begin();
4394 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004395 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4396 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004397 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004398 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4399 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004400 ++I;
4401 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004402 I = Data.FirstprivateCopies.begin();
4403 auto IElemInitRef = Data.FirstprivateInits.begin();
4404 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004405 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4406 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004407 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004408 PrivateHelpersTy(
4409 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4410 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004411 ++I;
4412 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004413 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004414 I = Data.LastprivateCopies.begin();
4415 for (auto *E : Data.LastprivateVars) {
4416 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4417 Privates.push_back(std::make_pair(
4418 C.getDeclAlign(VD),
4419 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4420 /*PrivateElemInit=*/nullptr)));
4421 ++I;
4422 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004423 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004424 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4425 // Build type kmp_routine_entry_t (if not built yet).
4426 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004427 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004428 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4429 if (SavedKmpTaskloopTQTy.isNull()) {
4430 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4431 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4432 }
4433 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004434 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004435 assert((D.getDirectiveKind() == OMPD_task ||
4436 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4437 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4438 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004439 if (SavedKmpTaskTQTy.isNull()) {
4440 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4441 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4442 }
4443 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004444 }
4445 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004446 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004447 auto *KmpTaskTWithPrivatesQTyRD =
4448 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4449 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4450 QualType KmpTaskTWithPrivatesPtrQTy =
4451 C.getPointerType(KmpTaskTWithPrivatesQTy);
4452 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4453 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004454 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004455 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4456
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004457 // Emit initial values for private copies (if any).
4458 llvm::Value *TaskPrivatesMap = nullptr;
4459 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004460 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004461 if (!Privates.empty()) {
4462 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004463 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4464 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4465 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004466 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4467 TaskPrivatesMap, TaskPrivatesMapTy);
4468 } else {
4469 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4470 cast<llvm::PointerType>(TaskPrivatesMapTy));
4471 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004472 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4473 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004474 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004475 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4476 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4477 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004478
4479 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4480 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4481 // kmp_routine_entry_t *task_entry);
4482 // Task flags. Format is taken from
4483 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4484 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004485 enum {
4486 TiedFlag = 0x1,
4487 FinalFlag = 0x2,
4488 DestructorsFlag = 0x8,
4489 PriorityFlag = 0x20
4490 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004491 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004492 bool NeedsCleanup = false;
4493 if (!Privates.empty()) {
4494 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4495 if (NeedsCleanup)
4496 Flags = Flags | DestructorsFlag;
4497 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004498 if (Data.Priority.getInt())
4499 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004500 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004501 Data.Final.getPointer()
4502 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004503 CGF.Builder.getInt32(FinalFlag),
4504 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004505 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004506 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004507 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004508 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4509 getThreadID(CGF, Loc), TaskFlags,
4510 KmpTaskTWithPrivatesTySize, SharedsSize,
4511 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4512 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004513 auto *NewTask = CGF.EmitRuntimeCall(
4514 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004515 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4516 NewTask, KmpTaskTWithPrivatesPtrTy);
4517 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4518 KmpTaskTWithPrivatesQTy);
4519 LValue TDBase =
4520 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004521 // Fill the data in the resulting kmp_task_t record.
4522 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004523 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004524 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004525 KmpTaskSharedsPtr =
4526 Address(CGF.EmitLoadOfScalar(
4527 CGF.EmitLValueForField(
4528 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4529 KmpTaskTShareds)),
4530 Loc),
4531 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004532 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004533 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004534 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004535 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004536 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004537 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4538 SharedsTy, SharedsPtrTy, Data, Privates,
4539 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004540 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4541 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4542 Result.TaskDupFn = emitTaskDupFunction(
4543 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4544 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4545 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004546 }
4547 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004548 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4549 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004550 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004551 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4552 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4553 if (NeedsCleanup) {
4554 llvm::Value *DestructorFn = emitDestructorsFunction(
4555 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4556 KmpTaskTWithPrivatesQTy);
4557 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4558 LValue DestructorsLV = CGF.EmitLValueForField(
4559 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4560 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4561 DestructorFn, KmpRoutineEntryPtrTy),
4562 DestructorsLV);
4563 }
4564 // Set priority.
4565 if (Data.Priority.getInt()) {
4566 LValue Data2LV = CGF.EmitLValueForField(
4567 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4568 LValue PriorityLV = CGF.EmitLValueForField(
4569 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4570 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4571 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004572 Result.NewTask = NewTask;
4573 Result.TaskEntry = TaskEntry;
4574 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4575 Result.TDBase = TDBase;
4576 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4577 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004578}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004579
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004580void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4581 const OMPExecutableDirective &D,
4582 llvm::Value *TaskFunction,
4583 QualType SharedsTy, Address Shareds,
4584 const Expr *IfCond,
4585 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004586 if (!CGF.HaveInsertPoint())
4587 return;
4588
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004589 TaskResultTy Result =
4590 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4591 llvm::Value *NewTask = Result.NewTask;
4592 llvm::Value *TaskEntry = Result.TaskEntry;
4593 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4594 LValue TDBase = Result.TDBase;
4595 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004596 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004597 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004598 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004599 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004600 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004601 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004602 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004603 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4604 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004605 QualType FlagsTy =
4606 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004607 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4608 if (KmpDependInfoTy.isNull()) {
4609 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4610 KmpDependInfoRD->startDefinition();
4611 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4612 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4613 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4614 KmpDependInfoRD->completeDefinition();
4615 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004616 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004617 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004618 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004619 // Define type kmp_depend_info[<Dependences.size()>];
4620 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004621 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004622 ArrayType::Normal, /*IndexTypeQuals=*/0);
4623 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004624 DependenciesArray =
4625 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004626 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004627 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004628 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004629 llvm::Value *Size;
4630 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004631 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4632 LValue UpAddrLVal =
4633 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4634 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004635 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004636 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004637 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004638 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4639 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004640 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004641 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004642 auto Base = CGF.MakeAddrLValue(
4643 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004644 KmpDependInfoTy);
4645 // deps[i].base_addr = &<Dependences[i].second>;
4646 auto BaseAddrLVal = CGF.EmitLValueForField(
4647 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004648 CGF.EmitStoreOfScalar(
4649 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4650 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004651 // deps[i].len = sizeof(<Dependences[i].second>);
4652 auto LenLVal = CGF.EmitLValueForField(
4653 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4654 CGF.EmitStoreOfScalar(Size, LenLVal);
4655 // deps[i].flags = <Dependences[i].first>;
4656 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004657 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004658 case OMPC_DEPEND_in:
4659 DepKind = DepIn;
4660 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004661 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004662 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004663 case OMPC_DEPEND_inout:
4664 DepKind = DepInOut;
4665 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004666 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004667 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004668 case OMPC_DEPEND_unknown:
4669 llvm_unreachable("Unknown task dependence type");
4670 }
4671 auto FlagsLVal = CGF.EmitLValueForField(
4672 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4673 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4674 FlagsLVal);
4675 }
John McCall7f416cc2015-09-08 08:05:57 +00004676 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4677 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004678 CGF.VoidPtrTy);
4679 }
4680
Alexey Bataev62b63b12015-03-10 07:28:44 +00004681 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4682 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004683 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4684 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4685 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4686 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004687 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004688 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004689 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4690 llvm::Value *DepTaskArgs[7];
4691 if (NumDependencies) {
4692 DepTaskArgs[0] = UpLoc;
4693 DepTaskArgs[1] = ThreadID;
4694 DepTaskArgs[2] = NewTask;
4695 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4696 DepTaskArgs[4] = DependenciesArray.getPointer();
4697 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4698 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4699 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004700 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4701 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004702 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004703 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004704 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4705 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4706 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4707 }
John McCall7f416cc2015-09-08 08:05:57 +00004708 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004709 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004710 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004711 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004712 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004713 TaskArgs);
4714 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004715 // Check if parent region is untied and build return for untied task;
4716 if (auto *Region =
4717 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4718 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004719 };
John McCall7f416cc2015-09-08 08:05:57 +00004720
4721 llvm::Value *DepWaitTaskArgs[6];
4722 if (NumDependencies) {
4723 DepWaitTaskArgs[0] = UpLoc;
4724 DepWaitTaskArgs[1] = ThreadID;
4725 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4726 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4727 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4728 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4729 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004730 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004731 NumDependencies, &DepWaitTaskArgs,
4732 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004733 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004734 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4735 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4736 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4737 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4738 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004739 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004740 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004741 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004742 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004743 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4744 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004745 Action.Enter(CGF);
4746 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004747 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004748 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004749 };
4750
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004751 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4752 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004753 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4754 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004755 RegionCodeGenTy RCG(CodeGen);
4756 CommonActionTy Action(
4757 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4758 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4759 RCG.setAction(Action);
4760 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004761 };
John McCall7f416cc2015-09-08 08:05:57 +00004762
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004763 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004764 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004765 else {
4766 RegionCodeGenTy ThenRCG(ThenCodeGen);
4767 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004768 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004769}
4770
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004771void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4772 const OMPLoopDirective &D,
4773 llvm::Value *TaskFunction,
4774 QualType SharedsTy, Address Shareds,
4775 const Expr *IfCond,
4776 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004777 if (!CGF.HaveInsertPoint())
4778 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004779 TaskResultTy Result =
4780 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004781 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4782 // libcall.
4783 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4784 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4785 // sched, kmp_uint64 grainsize, void *task_dup);
4786 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4787 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4788 llvm::Value *IfVal;
4789 if (IfCond) {
4790 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4791 /*isSigned=*/true);
4792 } else
4793 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4794
4795 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004796 Result.TDBase,
4797 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004798 auto *LBVar =
4799 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4800 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4801 /*IsInitializer=*/true);
4802 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004803 Result.TDBase,
4804 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004805 auto *UBVar =
4806 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4807 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4808 /*IsInitializer=*/true);
4809 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004810 Result.TDBase,
4811 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004812 auto *StVar =
4813 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4814 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4815 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004816 // Store reductions address.
4817 LValue RedLVal = CGF.EmitLValueForField(
4818 Result.TDBase,
4819 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4820 if (Data.Reductions)
4821 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4822 else {
4823 CGF.EmitNullInitialization(RedLVal.getAddress(),
4824 CGF.getContext().VoidPtrTy);
4825 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004826 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004827 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004828 UpLoc,
4829 ThreadID,
4830 Result.NewTask,
4831 IfVal,
4832 LBLVal.getPointer(),
4833 UBLVal.getPointer(),
4834 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4835 llvm::ConstantInt::getNullValue(
4836 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004837 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004838 CGF.IntTy, Data.Schedule.getPointer()
4839 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004840 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004841 Data.Schedule.getPointer()
4842 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004843 /*isSigned=*/false)
4844 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004845 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4846 Result.TaskDupFn, CGF.VoidPtrTy)
4847 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004848 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4849}
4850
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004851/// \brief Emit reduction operation for each element of array (required for
4852/// array sections) LHS op = RHS.
4853/// \param Type Type of array.
4854/// \param LHSVar Variable on the left side of the reduction operation
4855/// (references element of array in original variable).
4856/// \param RHSVar Variable on the right side of the reduction operation
4857/// (references element of array in original variable).
4858/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4859/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004860static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004861 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4862 const VarDecl *RHSVar,
4863 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4864 const Expr *, const Expr *)> &RedOpGen,
4865 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4866 const Expr *UpExpr = nullptr) {
4867 // Perform element-by-element initialization.
4868 QualType ElementTy;
4869 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4870 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4871
4872 // Drill down to the base element type on both arrays.
4873 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4874 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4875
4876 auto RHSBegin = RHSAddr.getPointer();
4877 auto LHSBegin = LHSAddr.getPointer();
4878 // Cast from pointer to array type to pointer to single element.
4879 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4880 // The basic structure here is a while-do loop.
4881 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4882 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4883 auto IsEmpty =
4884 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4885 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4886
4887 // Enter the loop body, making that address the current address.
4888 auto EntryBB = CGF.Builder.GetInsertBlock();
4889 CGF.EmitBlock(BodyBB);
4890
4891 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4892
4893 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4894 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4895 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4896 Address RHSElementCurrent =
4897 Address(RHSElementPHI,
4898 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4899
4900 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4901 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4902 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4903 Address LHSElementCurrent =
4904 Address(LHSElementPHI,
4905 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4906
4907 // Emit copy.
4908 CodeGenFunction::OMPPrivateScope Scope(CGF);
4909 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4910 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4911 Scope.Privatize();
4912 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4913 Scope.ForceCleanup();
4914
4915 // Shift the address forward by one element.
4916 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4917 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4918 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4919 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4920 // Check whether we've reached the end.
4921 auto Done =
4922 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4923 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4924 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4925 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4926
4927 // Done.
4928 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4929}
4930
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004931/// Emit reduction combiner. If the combiner is a simple expression emit it as
4932/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4933/// UDR combiner function.
4934static void emitReductionCombiner(CodeGenFunction &CGF,
4935 const Expr *ReductionOp) {
4936 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4937 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4938 if (auto *DRE =
4939 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4940 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4941 std::pair<llvm::Function *, llvm::Function *> Reduction =
4942 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4943 RValue Func = RValue::get(Reduction.first);
4944 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4945 CGF.EmitIgnoredExpr(ReductionOp);
4946 return;
4947 }
4948 CGF.EmitIgnoredExpr(ReductionOp);
4949}
4950
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004951llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004952 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
4953 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
4954 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004955 auto &C = CGM.getContext();
4956
4957 // void reduction_func(void *LHSArg, void *RHSArg);
4958 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004959 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
4960 ImplicitParamDecl::Other);
4961 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
4962 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004963 Args.push_back(&LHSArg);
4964 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004965 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004966 auto *Fn = llvm::Function::Create(
4967 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4968 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004969 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004970 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004971 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004972
4973 // Dst = (void*[n])(LHSArg);
4974 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004975 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4976 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4977 ArgsType), CGF.getPointerAlign());
4978 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4979 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4980 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004981
4982 // ...
4983 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4984 // ...
4985 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004986 auto IPriv = Privates.begin();
4987 unsigned Idx = 0;
4988 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004989 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4990 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004991 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004992 });
4993 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4994 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004995 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004996 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004997 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004998 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004999 // Get array size and emit VLA type.
5000 ++Idx;
5001 Address Elem =
5002 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5003 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005004 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
5005 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005006 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005007 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005008 CGF.EmitVariablyModifiedType(PrivTy);
5009 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005010 }
5011 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005012 IPriv = Privates.begin();
5013 auto ILHS = LHSExprs.begin();
5014 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005015 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005016 if ((*IPriv)->getType()->isArrayType()) {
5017 // Emit reduction for array section.
5018 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5019 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005020 EmitOMPAggregateReduction(
5021 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5022 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5023 emitReductionCombiner(CGF, E);
5024 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005025 } else
5026 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005027 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00005028 ++IPriv;
5029 ++ILHS;
5030 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005031 }
5032 Scope.ForceCleanup();
5033 CGF.FinishFunction();
5034 return Fn;
5035}
5036
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005037void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5038 const Expr *ReductionOp,
5039 const Expr *PrivateRef,
5040 const DeclRefExpr *LHS,
5041 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005042 if (PrivateRef->getType()->isArrayType()) {
5043 // Emit reduction for array section.
5044 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5045 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5046 EmitOMPAggregateReduction(
5047 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5048 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5049 emitReductionCombiner(CGF, ReductionOp);
5050 });
5051 } else
5052 // Emit reduction for array subscript or single variable.
5053 emitReductionCombiner(CGF, ReductionOp);
5054}
5055
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005056void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005057 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005058 ArrayRef<const Expr *> LHSExprs,
5059 ArrayRef<const Expr *> RHSExprs,
5060 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005061 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005062 if (!CGF.HaveInsertPoint())
5063 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005064
5065 bool WithNowait = Options.WithNowait;
5066 bool SimpleReduction = Options.SimpleReduction;
5067
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005068 // Next code should be emitted for reduction:
5069 //
5070 // static kmp_critical_name lock = { 0 };
5071 //
5072 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5073 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5074 // ...
5075 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5076 // *(Type<n>-1*)rhs[<n>-1]);
5077 // }
5078 //
5079 // ...
5080 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5081 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5082 // RedList, reduce_func, &<lock>)) {
5083 // case 1:
5084 // ...
5085 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5086 // ...
5087 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5088 // break;
5089 // case 2:
5090 // ...
5091 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5092 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005093 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005094 // break;
5095 // default:;
5096 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005097 //
5098 // if SimpleReduction is true, only the next code is generated:
5099 // ...
5100 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5101 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005102
5103 auto &C = CGM.getContext();
5104
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005105 if (SimpleReduction) {
5106 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005107 auto IPriv = Privates.begin();
5108 auto ILHS = LHSExprs.begin();
5109 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005110 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005111 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5112 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005113 ++IPriv;
5114 ++ILHS;
5115 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005116 }
5117 return;
5118 }
5119
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005120 // 1. Build a list of reduction variables.
5121 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005122 auto Size = RHSExprs.size();
5123 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005124 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005125 // Reserve place for array size.
5126 ++Size;
5127 }
5128 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005129 QualType ReductionArrayTy =
5130 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5131 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005132 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005133 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005134 auto IPriv = Privates.begin();
5135 unsigned Idx = 0;
5136 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005137 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005138 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005139 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005140 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005141 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5142 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005143 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005144 // Store array size.
5145 ++Idx;
5146 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5147 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005148 llvm::Value *Size = CGF.Builder.CreateIntCast(
5149 CGF.getVLASize(
5150 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5151 .first,
5152 CGF.SizeTy, /*isSigned=*/false);
5153 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5154 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005155 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005156 }
5157
5158 // 2. Emit reduce_func().
5159 auto *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005160 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5161 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005162
5163 // 3. Create static kmp_critical_name lock = { 0 };
5164 auto *Lock = getCriticalRegionLock(".reduction");
5165
5166 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5167 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005168 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005169 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005170 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005171 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5172 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005173 llvm::Value *Args[] = {
5174 IdentTLoc, // ident_t *<loc>
5175 ThreadId, // i32 <gtid>
5176 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5177 ReductionArrayTySize, // size_type sizeof(RedList)
5178 RL, // void *RedList
5179 ReductionFn, // void (*) (void *, void *) <reduce_func>
5180 Lock // kmp_critical_name *&<lock>
5181 };
5182 auto Res = CGF.EmitRuntimeCall(
5183 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5184 : OMPRTL__kmpc_reduce),
5185 Args);
5186
5187 // 5. Build switch(res)
5188 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5189 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5190
5191 // 6. Build case 1:
5192 // ...
5193 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5194 // ...
5195 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5196 // break;
5197 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5198 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5199 CGF.EmitBlock(Case1BB);
5200
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005201 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5202 llvm::Value *EndArgs[] = {
5203 IdentTLoc, // ident_t *<loc>
5204 ThreadId, // i32 <gtid>
5205 Lock // kmp_critical_name *&<lock>
5206 };
5207 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5208 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005209 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005210 auto IPriv = Privates.begin();
5211 auto ILHS = LHSExprs.begin();
5212 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005213 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005214 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5215 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005216 ++IPriv;
5217 ++ILHS;
5218 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005219 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005220 };
5221 RegionCodeGenTy RCG(CodeGen);
5222 CommonActionTy Action(
5223 nullptr, llvm::None,
5224 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5225 : OMPRTL__kmpc_end_reduce),
5226 EndArgs);
5227 RCG.setAction(Action);
5228 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005229
5230 CGF.EmitBranch(DefaultBB);
5231
5232 // 7. Build case 2:
5233 // ...
5234 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5235 // ...
5236 // break;
5237 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5238 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5239 CGF.EmitBlock(Case2BB);
5240
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005241 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5242 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005243 auto ILHS = LHSExprs.begin();
5244 auto IRHS = RHSExprs.begin();
5245 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005246 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005247 const Expr *XExpr = nullptr;
5248 const Expr *EExpr = nullptr;
5249 const Expr *UpExpr = nullptr;
5250 BinaryOperatorKind BO = BO_Comma;
5251 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5252 if (BO->getOpcode() == BO_Assign) {
5253 XExpr = BO->getLHS();
5254 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005255 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005256 }
5257 // Try to emit update expression as a simple atomic.
5258 auto *RHSExpr = UpExpr;
5259 if (RHSExpr) {
5260 // Analyze RHS part of the whole expression.
5261 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5262 RHSExpr->IgnoreParenImpCasts())) {
5263 // If this is a conditional operator, analyze its condition for
5264 // min/max reduction operator.
5265 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005266 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005267 if (auto *BORHS =
5268 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5269 EExpr = BORHS->getRHS();
5270 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005271 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005272 }
5273 if (XExpr) {
5274 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005275 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005276 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5277 const Expr *EExpr, const Expr *UpExpr) {
5278 LValue X = CGF.EmitLValue(XExpr);
5279 RValue E;
5280 if (EExpr)
5281 E = CGF.EmitAnyExpr(EExpr);
5282 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005283 X, E, BO, /*IsXLHSInRHSPart=*/true,
5284 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005285 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005286 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5287 PrivateScope.addPrivate(
5288 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5289 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5290 CGF.emitOMPSimpleStore(
5291 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5292 VD->getType().getNonReferenceType(), Loc);
5293 return LHSTemp;
5294 });
5295 (void)PrivateScope.Privatize();
5296 return CGF.EmitAnyExpr(UpExpr);
5297 });
5298 };
5299 if ((*IPriv)->getType()->isArrayType()) {
5300 // Emit atomic reduction for array section.
5301 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5302 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5303 AtomicRedGen, XExpr, EExpr, UpExpr);
5304 } else
5305 // Emit atomic reduction for array subscript or single variable.
5306 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5307 } else {
5308 // Emit as a critical region.
5309 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5310 const Expr *, const Expr *) {
5311 auto &RT = CGF.CGM.getOpenMPRuntime();
5312 RT.emitCriticalRegion(
5313 CGF, ".atomic_reduction",
5314 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5315 Action.Enter(CGF);
5316 emitReductionCombiner(CGF, E);
5317 },
5318 Loc);
5319 };
5320 if ((*IPriv)->getType()->isArrayType()) {
5321 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5322 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5323 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5324 CritRedGen);
5325 } else
5326 CritRedGen(CGF, nullptr, nullptr, nullptr);
5327 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005328 ++ILHS;
5329 ++IRHS;
5330 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005331 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005332 };
5333 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5334 if (!WithNowait) {
5335 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5336 llvm::Value *EndArgs[] = {
5337 IdentTLoc, // ident_t *<loc>
5338 ThreadId, // i32 <gtid>
5339 Lock // kmp_critical_name *&<lock>
5340 };
5341 CommonActionTy Action(nullptr, llvm::None,
5342 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5343 EndArgs);
5344 AtomicRCG.setAction(Action);
5345 AtomicRCG(CGF);
5346 } else
5347 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005348
5349 CGF.EmitBranch(DefaultBB);
5350 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5351}
5352
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005353/// Generates unique name for artificial threadprivate variables.
5354/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5355static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5356 unsigned N) {
5357 SmallString<256> Buffer;
5358 llvm::raw_svector_ostream Out(Buffer);
5359 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5360 return Out.str();
5361}
5362
5363/// Emits reduction initializer function:
5364/// \code
5365/// void @.red_init(void* %arg) {
5366/// %0 = bitcast void* %arg to <type>*
5367/// store <type> <init>, <type>* %0
5368/// ret void
5369/// }
5370/// \endcode
5371static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5372 SourceLocation Loc,
5373 ReductionCodeGen &RCG, unsigned N) {
5374 auto &C = CGM.getContext();
5375 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005376 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5377 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005378 Args.emplace_back(&Param);
5379 auto &FnInfo =
5380 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5381 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5382 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5383 ".red_init.", &CGM.getModule());
5384 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5385 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005386 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005387 Address PrivateAddr = CGF.EmitLoadOfPointer(
5388 CGF.GetAddrOfLocalVar(&Param),
5389 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5390 llvm::Value *Size = nullptr;
5391 // If the size of the reduction item is non-constant, load it from global
5392 // threadprivate variable.
5393 if (RCG.getSizes(N).second) {
5394 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5395 CGF, CGM.getContext().getSizeType(),
5396 generateUniqueName("reduction_size", Loc, N));
5397 Size =
5398 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5399 CGM.getContext().getSizeType(), SourceLocation());
5400 }
5401 RCG.emitAggregateType(CGF, N, Size);
5402 LValue SharedLVal;
5403 // If initializer uses initializer from declare reduction construct, emit a
5404 // pointer to the address of the original reduction item (reuired by reduction
5405 // initializer)
5406 if (RCG.usesReductionInitializer(N)) {
5407 Address SharedAddr =
5408 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5409 CGF, CGM.getContext().VoidPtrTy,
5410 generateUniqueName("reduction", Loc, N));
5411 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5412 } else {
5413 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5414 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5415 CGM.getContext().VoidPtrTy);
5416 }
5417 // Emit the initializer:
5418 // %0 = bitcast void* %arg to <type>*
5419 // store <type> <init>, <type>* %0
5420 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5421 [](CodeGenFunction &) { return false; });
5422 CGF.FinishFunction();
5423 return Fn;
5424}
5425
5426/// Emits reduction combiner function:
5427/// \code
5428/// void @.red_comb(void* %arg0, void* %arg1) {
5429/// %lhs = bitcast void* %arg0 to <type>*
5430/// %rhs = bitcast void* %arg1 to <type>*
5431/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5432/// store <type> %2, <type>* %lhs
5433/// ret void
5434/// }
5435/// \endcode
5436static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5437 SourceLocation Loc,
5438 ReductionCodeGen &RCG, unsigned N,
5439 const Expr *ReductionOp,
5440 const Expr *LHS, const Expr *RHS,
5441 const Expr *PrivateRef) {
5442 auto &C = CGM.getContext();
5443 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5444 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5445 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005446 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5447 C.VoidPtrTy, ImplicitParamDecl::Other);
5448 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5449 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005450 Args.emplace_back(&ParamInOut);
5451 Args.emplace_back(&ParamIn);
5452 auto &FnInfo =
5453 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5454 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5455 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5456 ".red_comb.", &CGM.getModule());
5457 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5458 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005459 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005460 llvm::Value *Size = nullptr;
5461 // If the size of the reduction item is non-constant, load it from global
5462 // threadprivate variable.
5463 if (RCG.getSizes(N).second) {
5464 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5465 CGF, CGM.getContext().getSizeType(),
5466 generateUniqueName("reduction_size", Loc, N));
5467 Size =
5468 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5469 CGM.getContext().getSizeType(), SourceLocation());
5470 }
5471 RCG.emitAggregateType(CGF, N, Size);
5472 // Remap lhs and rhs variables to the addresses of the function arguments.
5473 // %lhs = bitcast void* %arg0 to <type>*
5474 // %rhs = bitcast void* %arg1 to <type>*
5475 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5476 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5477 // Pull out the pointer to the variable.
5478 Address PtrAddr = CGF.EmitLoadOfPointer(
5479 CGF.GetAddrOfLocalVar(&ParamInOut),
5480 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5481 return CGF.Builder.CreateElementBitCast(
5482 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5483 });
5484 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5485 // Pull out the pointer to the variable.
5486 Address PtrAddr = CGF.EmitLoadOfPointer(
5487 CGF.GetAddrOfLocalVar(&ParamIn),
5488 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5489 return CGF.Builder.CreateElementBitCast(
5490 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5491 });
5492 PrivateScope.Privatize();
5493 // Emit the combiner body:
5494 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5495 // store <type> %2, <type>* %lhs
5496 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5497 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5498 cast<DeclRefExpr>(RHS));
5499 CGF.FinishFunction();
5500 return Fn;
5501}
5502
5503/// Emits reduction finalizer function:
5504/// \code
5505/// void @.red_fini(void* %arg) {
5506/// %0 = bitcast void* %arg to <type>*
5507/// <destroy>(<type>* %0)
5508/// ret void
5509/// }
5510/// \endcode
5511static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5512 SourceLocation Loc,
5513 ReductionCodeGen &RCG, unsigned N) {
5514 if (!RCG.needCleanups(N))
5515 return nullptr;
5516 auto &C = CGM.getContext();
5517 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005518 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5519 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005520 Args.emplace_back(&Param);
5521 auto &FnInfo =
5522 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5523 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5524 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5525 ".red_fini.", &CGM.getModule());
5526 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5527 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005528 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005529 Address PrivateAddr = CGF.EmitLoadOfPointer(
5530 CGF.GetAddrOfLocalVar(&Param),
5531 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5532 llvm::Value *Size = nullptr;
5533 // If the size of the reduction item is non-constant, load it from global
5534 // threadprivate variable.
5535 if (RCG.getSizes(N).second) {
5536 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5537 CGF, CGM.getContext().getSizeType(),
5538 generateUniqueName("reduction_size", Loc, N));
5539 Size =
5540 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5541 CGM.getContext().getSizeType(), SourceLocation());
5542 }
5543 RCG.emitAggregateType(CGF, N, Size);
5544 // Emit the finalizer body:
5545 // <destroy>(<type>* %0)
5546 RCG.emitCleanups(CGF, N, PrivateAddr);
5547 CGF.FinishFunction();
5548 return Fn;
5549}
5550
5551llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5552 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5553 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5554 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5555 return nullptr;
5556
5557 // Build typedef struct:
5558 // kmp_task_red_input {
5559 // void *reduce_shar; // shared reduction item
5560 // size_t reduce_size; // size of data item
5561 // void *reduce_init; // data initialization routine
5562 // void *reduce_fini; // data finalization routine
5563 // void *reduce_comb; // data combiner routine
5564 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5565 // } kmp_task_red_input_t;
5566 ASTContext &C = CGM.getContext();
5567 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5568 RD->startDefinition();
5569 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5570 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5571 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5572 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5573 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5574 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5575 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5576 RD->completeDefinition();
5577 QualType RDType = C.getRecordType(RD);
5578 unsigned Size = Data.ReductionVars.size();
5579 llvm::APInt ArraySize(/*numBits=*/64, Size);
5580 QualType ArrayRDType = C.getConstantArrayType(
5581 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5582 // kmp_task_red_input_t .rd_input.[Size];
5583 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5584 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5585 Data.ReductionOps);
5586 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5587 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5588 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5589 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5590 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5591 TaskRedInput.getPointer(), Idxs,
5592 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5593 ".rd_input.gep.");
5594 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5595 // ElemLVal.reduce_shar = &Shareds[Cnt];
5596 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5597 RCG.emitSharedLValue(CGF, Cnt);
5598 llvm::Value *CastedShared =
5599 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5600 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5601 RCG.emitAggregateType(CGF, Cnt);
5602 llvm::Value *SizeValInChars;
5603 llvm::Value *SizeVal;
5604 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5605 // We use delayed creation/initialization for VLAs, array sections and
5606 // custom reduction initializations. It is required because runtime does not
5607 // provide the way to pass the sizes of VLAs/array sections to
5608 // initializer/combiner/finalizer functions and does not pass the pointer to
5609 // original reduction item to the initializer. Instead threadprivate global
5610 // variables are used to store these values and use them in the functions.
5611 bool DelayedCreation = !!SizeVal;
5612 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5613 /*isSigned=*/false);
5614 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5615 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5616 // ElemLVal.reduce_init = init;
5617 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5618 llvm::Value *InitAddr =
5619 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5620 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5621 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5622 // ElemLVal.reduce_fini = fini;
5623 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5624 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5625 llvm::Value *FiniAddr = Fini
5626 ? CGF.EmitCastToVoidPtr(Fini)
5627 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5628 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5629 // ElemLVal.reduce_comb = comb;
5630 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5631 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5632 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5633 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5634 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5635 // ElemLVal.flags = 0;
5636 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5637 if (DelayedCreation) {
5638 CGF.EmitStoreOfScalar(
5639 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5640 FlagsLVal);
5641 } else
5642 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5643 }
5644 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5645 // *data);
5646 llvm::Value *Args[] = {
5647 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5648 /*isSigned=*/true),
5649 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5650 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5651 CGM.VoidPtrTy)};
5652 return CGF.EmitRuntimeCall(
5653 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5654}
5655
5656void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5657 SourceLocation Loc,
5658 ReductionCodeGen &RCG,
5659 unsigned N) {
5660 auto Sizes = RCG.getSizes(N);
5661 // Emit threadprivate global variable if the type is non-constant
5662 // (Sizes.second = nullptr).
5663 if (Sizes.second) {
5664 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5665 /*isSigned=*/false);
5666 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5667 CGF, CGM.getContext().getSizeType(),
5668 generateUniqueName("reduction_size", Loc, N));
5669 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5670 }
5671 // Store address of the original reduction item if custom initializer is used.
5672 if (RCG.usesReductionInitializer(N)) {
5673 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5674 CGF, CGM.getContext().VoidPtrTy,
5675 generateUniqueName("reduction", Loc, N));
5676 CGF.Builder.CreateStore(
5677 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5678 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5679 SharedAddr, /*IsVolatile=*/false);
5680 }
5681}
5682
5683Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5684 SourceLocation Loc,
5685 llvm::Value *ReductionsPtr,
5686 LValue SharedLVal) {
5687 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5688 // *d);
5689 llvm::Value *Args[] = {
5690 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5691 /*isSigned=*/true),
5692 ReductionsPtr,
5693 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5694 CGM.VoidPtrTy)};
5695 return Address(
5696 CGF.EmitRuntimeCall(
5697 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5698 SharedLVal.getAlignment());
5699}
5700
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005701void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5702 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005703 if (!CGF.HaveInsertPoint())
5704 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005705 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5706 // global_tid);
5707 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5708 // Ignore return result until untied tasks are supported.
5709 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005710 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5711 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005712}
5713
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005714void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005715 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005716 const RegionCodeGenTy &CodeGen,
5717 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005718 if (!CGF.HaveInsertPoint())
5719 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005720 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005721 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005722}
5723
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005724namespace {
5725enum RTCancelKind {
5726 CancelNoreq = 0,
5727 CancelParallel = 1,
5728 CancelLoop = 2,
5729 CancelSections = 3,
5730 CancelTaskgroup = 4
5731};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005732} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005733
5734static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5735 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005736 if (CancelRegion == OMPD_parallel)
5737 CancelKind = CancelParallel;
5738 else if (CancelRegion == OMPD_for)
5739 CancelKind = CancelLoop;
5740 else if (CancelRegion == OMPD_sections)
5741 CancelKind = CancelSections;
5742 else {
5743 assert(CancelRegion == OMPD_taskgroup);
5744 CancelKind = CancelTaskgroup;
5745 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005746 return CancelKind;
5747}
5748
5749void CGOpenMPRuntime::emitCancellationPointCall(
5750 CodeGenFunction &CGF, SourceLocation Loc,
5751 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005752 if (!CGF.HaveInsertPoint())
5753 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005754 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5755 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005756 if (auto *OMPRegionInfo =
5757 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005758 // For 'cancellation point taskgroup', the task region info may not have a
5759 // cancel. This may instead happen in another adjacent task.
5760 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005761 llvm::Value *Args[] = {
5762 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5763 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005764 // Ignore return result until untied tasks are supported.
5765 auto *Result = CGF.EmitRuntimeCall(
5766 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5767 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005768 // exit from construct;
5769 // }
5770 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5771 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5772 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5773 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5774 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005775 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005776 auto CancelDest =
5777 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005778 CGF.EmitBranchThroughCleanup(CancelDest);
5779 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5780 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005781 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005782}
5783
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005784void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005785 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005786 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005787 if (!CGF.HaveInsertPoint())
5788 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005789 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5790 // kmp_int32 cncl_kind);
5791 if (auto *OMPRegionInfo =
5792 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005793 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5794 PrePostActionTy &) {
5795 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005796 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005797 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005798 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5799 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005800 auto *Result = CGF.EmitRuntimeCall(
5801 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005802 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005803 // exit from construct;
5804 // }
5805 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5806 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5807 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5808 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5809 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005810 // exit from construct;
5811 auto CancelDest =
5812 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5813 CGF.EmitBranchThroughCleanup(CancelDest);
5814 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5815 };
5816 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005817 emitOMPIfClause(CGF, IfCond, ThenGen,
5818 [](CodeGenFunction &, PrePostActionTy &) {});
5819 else {
5820 RegionCodeGenTy ThenRCG(ThenGen);
5821 ThenRCG(CGF);
5822 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005823 }
5824}
Samuel Antaobed3c462015-10-02 16:14:20 +00005825
Samuel Antaoee8fb302016-01-06 13:42:12 +00005826/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005827/// consists of the file and device IDs as well as line number associated with
5828/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005829static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5830 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005831 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005832
5833 auto &SM = C.getSourceManager();
5834
5835 // The loc should be always valid and have a file ID (the user cannot use
5836 // #pragma directives in macros)
5837
5838 assert(Loc.isValid() && "Source location is expected to be always valid.");
5839 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5840
5841 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5842 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5843
5844 llvm::sys::fs::UniqueID ID;
5845 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5846 llvm_unreachable("Source file with target region no longer exists!");
5847
5848 DeviceID = ID.getDevice();
5849 FileID = ID.getFile();
5850 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005851}
5852
5853void CGOpenMPRuntime::emitTargetOutlinedFunction(
5854 const OMPExecutableDirective &D, StringRef ParentName,
5855 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005856 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005857 assert(!ParentName.empty() && "Invalid target region parent name!");
5858
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005859 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5860 IsOffloadEntry, CodeGen);
5861}
5862
5863void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5864 const OMPExecutableDirective &D, StringRef ParentName,
5865 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5866 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005867 // Create a unique name for the entry function using the source location
5868 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005869 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005870 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005871 //
5872 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005873 // mangled name of the function that encloses the target region and BB is the
5874 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005875
5876 unsigned DeviceID;
5877 unsigned FileID;
5878 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005879 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005880 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005881 SmallString<64> EntryFnName;
5882 {
5883 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005884 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5885 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005886 }
5887
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005888 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5889
Samuel Antaobed3c462015-10-02 16:14:20 +00005890 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005891 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005892 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005893
Samuel Antao6d004262016-06-16 18:39:34 +00005894 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005895
5896 // If this target outline function is not an offload entry, we don't need to
5897 // register it.
5898 if (!IsOffloadEntry)
5899 return;
5900
5901 // The target region ID is used by the runtime library to identify the current
5902 // target region, so it only has to be unique and not necessarily point to
5903 // anything. It could be the pointer to the outlined function that implements
5904 // the target region, but we aren't using that so that the compiler doesn't
5905 // need to keep that, and could therefore inline the host function if proven
5906 // worthwhile during optimization. In the other hand, if emitting code for the
5907 // device, the ID has to be the function address so that it can retrieved from
5908 // the offloading entry and launched by the runtime library. We also mark the
5909 // outlined function to have external linkage in case we are emitting code for
5910 // the device, because these functions will be entry points to the device.
5911
5912 if (CGM.getLangOpts().OpenMPIsDevice) {
5913 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5914 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5915 } else
5916 OutlinedFnID = new llvm::GlobalVariable(
5917 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5918 llvm::GlobalValue::PrivateLinkage,
5919 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5920
5921 // Register the information for the entry associated with this target region.
5922 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005923 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5924 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005925}
5926
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005927/// discard all CompoundStmts intervening between two constructs
5928static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5929 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5930 Body = CS->body_front();
5931
5932 return Body;
5933}
5934
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005935/// Emit the number of teams for a target directive. Inspect the num_teams
5936/// clause associated with a teams construct combined or closely nested
5937/// with the target directive.
5938///
5939/// Emit a team of size one for directives such as 'target parallel' that
5940/// have no associated teams construct.
5941///
5942/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005943static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005944emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5945 CodeGenFunction &CGF,
5946 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005947
5948 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5949 "teams directive expected to be "
5950 "emitted only for the host!");
5951
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005952 auto &Bld = CGF.Builder;
5953
5954 // If the target directive is combined with a teams directive:
5955 // Return the value in the num_teams clause, if any.
5956 // Otherwise, return 0 to denote the runtime default.
5957 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5958 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5959 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5960 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5961 /*IgnoreResultAssign*/ true);
5962 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5963 /*IsSigned=*/true);
5964 }
5965
5966 // The default value is 0.
5967 return Bld.getInt32(0);
5968 }
5969
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005970 // If the target directive is combined with a parallel directive but not a
5971 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005972 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5973 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005974
5975 // If the current target region has a teams region enclosed, we need to get
5976 // the number of teams to pass to the runtime function call. This is done
5977 // by generating the expression in a inlined region. This is required because
5978 // the expression is captured in the enclosing target environment when the
5979 // teams directive is not combined with target.
5980
5981 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5982
Alexey Bataev50a1c782017-12-01 21:31:08 +00005983 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005984 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00005985 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
5986 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5987 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5988 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5989 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
5990 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5991 /*IsSigned=*/true);
5992 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00005993
Alexey Bataev50a1c782017-12-01 21:31:08 +00005994 // If we have an enclosed teams directive but no num_teams clause we use
5995 // the default value 0.
5996 return Bld.getInt32(0);
5997 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00005998 }
5999
6000 // No teams associated with the directive.
6001 return nullptr;
6002}
6003
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006004/// Emit the number of threads for a target directive. Inspect the
6005/// thread_limit clause associated with a teams construct combined or closely
6006/// nested with the target directive.
6007///
6008/// Emit the num_threads clause for directives such as 'target parallel' that
6009/// have no associated teams construct.
6010///
6011/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006012static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006013emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6014 CodeGenFunction &CGF,
6015 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006016
6017 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6018 "teams directive expected to be "
6019 "emitted only for the host!");
6020
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006021 auto &Bld = CGF.Builder;
6022
6023 //
6024 // If the target directive is combined with a teams directive:
6025 // Return the value in the thread_limit clause, if any.
6026 //
6027 // If the target directive is combined with a parallel directive:
6028 // Return the value in the num_threads clause, if any.
6029 //
6030 // If both clauses are set, select the minimum of the two.
6031 //
6032 // If neither teams or parallel combined directives set the number of threads
6033 // in a team, return 0 to denote the runtime default.
6034 //
6035 // If this is not a teams directive return nullptr.
6036
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006037 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6038 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006039 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6040 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006041 llvm::Value *ThreadLimitVal = nullptr;
6042
6043 if (const auto *ThreadLimitClause =
6044 D.getSingleClause<OMPThreadLimitClause>()) {
6045 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6046 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6047 /*IgnoreResultAssign*/ true);
6048 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6049 /*IsSigned=*/true);
6050 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006051
6052 if (const auto *NumThreadsClause =
6053 D.getSingleClause<OMPNumThreadsClause>()) {
6054 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6055 llvm::Value *NumThreads =
6056 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6057 /*IgnoreResultAssign*/ true);
6058 NumThreadsVal =
6059 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6060 }
6061
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006062 // Select the lesser of thread_limit and num_threads.
6063 if (NumThreadsVal)
6064 ThreadLimitVal = ThreadLimitVal
6065 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6066 ThreadLimitVal),
6067 NumThreadsVal, ThreadLimitVal)
6068 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006069
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006070 // Set default value passed to the runtime if either teams or a target
6071 // parallel type directive is found but no clause is specified.
6072 if (!ThreadLimitVal)
6073 ThreadLimitVal = DefaultThreadLimitVal;
6074
6075 return ThreadLimitVal;
6076 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006077
Samuel Antaob68e2db2016-03-03 16:20:23 +00006078 // If the current target region has a teams region enclosed, we need to get
6079 // the thread limit to pass to the runtime function call. This is done
6080 // by generating the expression in a inlined region. This is required because
6081 // the expression is captured in the enclosing target environment when the
6082 // teams directive is not combined with target.
6083
6084 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6085
Alexey Bataev50a1c782017-12-01 21:31:08 +00006086 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006087 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006088 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6089 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
6090 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6091 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6092 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6093 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6094 /*IsSigned=*/true);
6095 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006096
Alexey Bataev50a1c782017-12-01 21:31:08 +00006097 // If we have an enclosed teams directive but no thread_limit clause we
6098 // use the default value 0.
6099 return CGF.Builder.getInt32(0);
6100 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006101 }
6102
6103 // No teams associated with the directive.
6104 return nullptr;
6105}
6106
Samuel Antao86ace552016-04-27 22:40:57 +00006107namespace {
6108// \brief Utility to handle information from clauses associated with a given
6109// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6110// It provides a convenient interface to obtain the information and generate
6111// code for that information.
6112class MappableExprsHandler {
6113public:
6114 /// \brief Values for bit flags used to specify the mapping type for
6115 /// offloading.
6116 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006117 /// \brief Allocate memory on the device and move data from host to device.
6118 OMP_MAP_TO = 0x01,
6119 /// \brief Allocate memory on the device and move data from device to host.
6120 OMP_MAP_FROM = 0x02,
6121 /// \brief Always perform the requested mapping action on the element, even
6122 /// if it was already mapped before.
6123 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006124 /// \brief Delete the element from the device environment, ignoring the
6125 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006126 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006127 /// \brief The element being mapped is a pointer-pointee pair; both the
6128 /// pointer and the pointee should be mapped.
6129 OMP_MAP_PTR_AND_OBJ = 0x10,
6130 /// \brief This flags signals that the base address of an entry should be
6131 /// passed to the target kernel as an argument.
6132 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006133 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006134 /// in the current position for the data being mapped. Used when we have the
6135 /// use_device_ptr clause.
6136 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006137 /// \brief This flag signals that the reference being passed is a pointer to
6138 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006139 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006140 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006141 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006142 /// Implicit map
6143 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006144 };
6145
Samuel Antaocc10b852016-07-28 14:23:26 +00006146 /// Class that associates information with a base pointer to be passed to the
6147 /// runtime library.
6148 class BasePointerInfo {
6149 /// The base pointer.
6150 llvm::Value *Ptr = nullptr;
6151 /// The base declaration that refers to this device pointer, or null if
6152 /// there is none.
6153 const ValueDecl *DevPtrDecl = nullptr;
6154
6155 public:
6156 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6157 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6158 llvm::Value *operator*() const { return Ptr; }
6159 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6160 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6161 };
6162
6163 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006164 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006165 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006166
6167private:
6168 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006169 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006170
6171 /// \brief Function the directive is being generated for.
6172 CodeGenFunction &CGF;
6173
Samuel Antaod486f842016-05-26 16:53:38 +00006174 /// \brief Set of all first private variables in the current directive.
6175 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006176 /// Set of all reduction variables in the current directive.
6177 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006178
Samuel Antao6890b092016-07-28 14:25:09 +00006179 /// Map between device pointer declarations and their expression components.
6180 /// The key value for declarations in 'this' is null.
6181 llvm::DenseMap<
6182 const ValueDecl *,
6183 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6184 DevPointersMap;
6185
Samuel Antao86ace552016-04-27 22:40:57 +00006186 llvm::Value *getExprTypeSize(const Expr *E) const {
6187 auto ExprTy = E->getType().getCanonicalType();
6188
6189 // Reference types are ignored for mapping purposes.
6190 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6191 ExprTy = RefTy->getPointeeType().getCanonicalType();
6192
6193 // Given that an array section is considered a built-in type, we need to
6194 // do the calculation based on the length of the section instead of relying
6195 // on CGF.getTypeSize(E->getType()).
6196 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6197 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6198 OAE->getBase()->IgnoreParenImpCasts())
6199 .getCanonicalType();
6200
6201 // If there is no length associated with the expression, that means we
6202 // are using the whole length of the base.
6203 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6204 return CGF.getTypeSize(BaseTy);
6205
6206 llvm::Value *ElemSize;
6207 if (auto *PTy = BaseTy->getAs<PointerType>())
6208 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6209 else {
6210 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6211 assert(ATy && "Expecting array type if not a pointer type.");
6212 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6213 }
6214
6215 // If we don't have a length at this point, that is because we have an
6216 // array section with a single element.
6217 if (!OAE->getLength())
6218 return ElemSize;
6219
6220 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6221 LengthVal =
6222 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6223 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6224 }
6225 return CGF.getTypeSize(ExprTy);
6226 }
6227
6228 /// \brief Return the corresponding bits for a given map clause modifier. Add
6229 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006230 /// map as the first one of a series of maps that relate to the same map
6231 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006232 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006233 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006234 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006235 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006236 switch (MapType) {
6237 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006238 case OMPC_MAP_release:
6239 // alloc and release is the default behavior in the runtime library, i.e.
6240 // if we don't pass any bits alloc/release that is what the runtime is
6241 // going to do. Therefore, we don't need to signal anything for these two
6242 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006243 break;
6244 case OMPC_MAP_to:
6245 Bits = OMP_MAP_TO;
6246 break;
6247 case OMPC_MAP_from:
6248 Bits = OMP_MAP_FROM;
6249 break;
6250 case OMPC_MAP_tofrom:
6251 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6252 break;
6253 case OMPC_MAP_delete:
6254 Bits = OMP_MAP_DELETE;
6255 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006256 default:
6257 llvm_unreachable("Unexpected map type!");
6258 break;
6259 }
6260 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006261 Bits |= OMP_MAP_PTR_AND_OBJ;
6262 if (AddIsTargetParamFlag)
6263 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006264 if (MapTypeModifier == OMPC_MAP_always)
6265 Bits |= OMP_MAP_ALWAYS;
6266 return Bits;
6267 }
6268
6269 /// \brief Return true if the provided expression is a final array section. A
6270 /// final array section, is one whose length can't be proved to be one.
6271 bool isFinalArraySectionExpression(const Expr *E) const {
6272 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6273
6274 // It is not an array section and therefore not a unity-size one.
6275 if (!OASE)
6276 return false;
6277
6278 // An array section with no colon always refer to a single element.
6279 if (OASE->getColonLoc().isInvalid())
6280 return false;
6281
6282 auto *Length = OASE->getLength();
6283
6284 // If we don't have a length we have to check if the array has size 1
6285 // for this dimension. Also, we should always expect a length if the
6286 // base type is pointer.
6287 if (!Length) {
6288 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6289 OASE->getBase()->IgnoreParenImpCasts())
6290 .getCanonicalType();
6291 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6292 return ATy->getSize().getSExtValue() != 1;
6293 // If we don't have a constant dimension length, we have to consider
6294 // the current section as having any size, so it is not necessarily
6295 // unitary. If it happen to be unity size, that's user fault.
6296 return true;
6297 }
6298
6299 // Check if the length evaluates to 1.
6300 llvm::APSInt ConstLength;
6301 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6302 return true; // Can have more that size 1.
6303
6304 return ConstLength.getSExtValue() != 1;
6305 }
6306
6307 /// \brief Generate the base pointers, section pointers, sizes and map type
6308 /// bits for the provided map type, map modifier, and expression components.
6309 /// \a IsFirstComponent should be set to true if the provided set of
6310 /// components is the first associated with a capture.
6311 void generateInfoForComponentList(
6312 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6313 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006314 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006315 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006316 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006317
6318 // The following summarizes what has to be generated for each map and the
6319 // types bellow. The generated information is expressed in this order:
6320 // base pointer, section pointer, size, flags
6321 // (to add to the ones that come from the map type and modifier).
6322 //
6323 // double d;
6324 // int i[100];
6325 // float *p;
6326 //
6327 // struct S1 {
6328 // int i;
6329 // float f[50];
6330 // }
6331 // struct S2 {
6332 // int i;
6333 // float f[50];
6334 // S1 s;
6335 // double *p;
6336 // struct S2 *ps;
6337 // }
6338 // S2 s;
6339 // S2 *ps;
6340 //
6341 // map(d)
6342 // &d, &d, sizeof(double), noflags
6343 //
6344 // map(i)
6345 // &i, &i, 100*sizeof(int), noflags
6346 //
6347 // map(i[1:23])
6348 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6349 //
6350 // map(p)
6351 // &p, &p, sizeof(float*), noflags
6352 //
6353 // map(p[1:24])
6354 // p, &p[1], 24*sizeof(float), noflags
6355 //
6356 // map(s)
6357 // &s, &s, sizeof(S2), noflags
6358 //
6359 // map(s.i)
6360 // &s, &(s.i), sizeof(int), noflags
6361 //
6362 // map(s.s.f)
6363 // &s, &(s.i.f), 50*sizeof(int), noflags
6364 //
6365 // map(s.p)
6366 // &s, &(s.p), sizeof(double*), noflags
6367 //
6368 // map(s.p[:22], s.a s.b)
6369 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006370 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006371 //
6372 // map(s.ps)
6373 // &s, &(s.ps), sizeof(S2*), noflags
6374 //
6375 // map(s.ps->s.i)
6376 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006377 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006378 //
6379 // map(s.ps->ps)
6380 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006381 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006382 //
6383 // map(s.ps->ps->ps)
6384 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006385 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6386 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006387 //
6388 // map(s.ps->ps->s.f[:22])
6389 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006390 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6391 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006392 //
6393 // map(ps)
6394 // &ps, &ps, sizeof(S2*), noflags
6395 //
6396 // map(ps->i)
6397 // ps, &(ps->i), sizeof(int), noflags
6398 //
6399 // map(ps->s.f)
6400 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6401 //
6402 // map(ps->p)
6403 // ps, &(ps->p), sizeof(double*), noflags
6404 //
6405 // map(ps->p[:22])
6406 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006407 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006408 //
6409 // map(ps->ps)
6410 // ps, &(ps->ps), sizeof(S2*), noflags
6411 //
6412 // map(ps->ps->s.i)
6413 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006414 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006415 //
6416 // map(ps->ps->ps)
6417 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006418 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006419 //
6420 // map(ps->ps->ps->ps)
6421 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006422 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6423 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006424 //
6425 // map(ps->ps->ps->s.f[:22])
6426 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006427 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6428 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006429
6430 // Track if the map information being generated is the first for a capture.
6431 bool IsCaptureFirstInfo = IsFirstComponentList;
6432
6433 // Scan the components from the base to the complete expression.
6434 auto CI = Components.rbegin();
6435 auto CE = Components.rend();
6436 auto I = CI;
6437
6438 // Track if the map information being generated is the first for a list of
6439 // components.
6440 bool IsExpressionFirstInfo = true;
6441 llvm::Value *BP = nullptr;
6442
6443 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6444 // The base is the 'this' pointer. The content of the pointer is going
6445 // to be the base of the field being mapped.
6446 BP = CGF.EmitScalarExpr(ME->getBase());
6447 } else {
6448 // The base is the reference to the variable.
6449 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006450 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006451
6452 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006453 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006454 // reference. References are ignored for mapping purposes.
6455 QualType Ty =
6456 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6457 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6458 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006459 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006460 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006461 .getPointer();
6462
6463 // We do not need to generate individual map information for the
6464 // pointer, it can be associated with the combined storage.
6465 ++I;
6466 }
6467 }
6468
George Rokos63bc9d62017-11-21 18:25:12 +00006469 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006470 for (; I != CE; ++I) {
6471 auto Next = std::next(I);
6472
6473 // We need to generate the addresses and sizes if this is the last
6474 // component, if the component is a pointer or if it is an array section
6475 // whose length can't be proved to be one. If this is a pointer, it
6476 // becomes the base address for the following components.
6477
6478 // A final array section, is one whose length can't be proved to be one.
6479 bool IsFinalArraySection =
6480 isFinalArraySectionExpression(I->getAssociatedExpression());
6481
6482 // Get information on whether the element is a pointer. Have to do a
6483 // special treatment for array sections given that they are built-in
6484 // types.
6485 const auto *OASE =
6486 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6487 bool IsPointer =
6488 (OASE &&
6489 OMPArraySectionExpr::getBaseOriginalType(OASE)
6490 .getCanonicalType()
6491 ->isAnyPointerType()) ||
6492 I->getAssociatedExpression()->getType()->isAnyPointerType();
6493
6494 if (Next == CE || IsPointer || IsFinalArraySection) {
6495
6496 // If this is not the last component, we expect the pointer to be
6497 // associated with an array expression or member expression.
6498 assert((Next == CE ||
6499 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6500 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6501 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6502 "Unexpected expression");
6503
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006504 llvm::Value *LB =
6505 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006506 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6507
Samuel Antao03a3cec2016-07-27 22:52:16 +00006508 // If we have a member expression and the current component is a
6509 // reference, we have to map the reference too. Whenever we have a
6510 // reference, the section that reference refers to is going to be a
6511 // load instruction from the storage assigned to the reference.
6512 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6513 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6514 auto *LI = cast<llvm::LoadInst>(LB);
6515 auto *RefAddr = LI->getPointerOperand();
6516
6517 BasePointers.push_back(BP);
6518 Pointers.push_back(RefAddr);
6519 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006520 Types.push_back(DefaultFlags |
6521 getMapTypeBits(
6522 /*MapType*/ OMPC_MAP_alloc,
6523 /*MapTypeModifier=*/OMPC_MAP_unknown,
6524 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006525 IsExpressionFirstInfo = false;
6526 IsCaptureFirstInfo = false;
6527 // The reference will be the next base address.
6528 BP = RefAddr;
6529 }
6530
6531 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006532 Pointers.push_back(LB);
6533 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006534
Samuel Antao6782e942016-05-26 16:48:10 +00006535 // We need to add a pointer flag for each map that comes from the
6536 // same expression except for the first one. We also need to signal
6537 // this map is the first one that relates with the current capture
6538 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006539 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6540 !IsExpressionFirstInfo,
6541 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006542
6543 // If we have a final array section, we are done with this expression.
6544 if (IsFinalArraySection)
6545 break;
6546
6547 // The pointer becomes the base for the next element.
6548 if (Next != CE)
6549 BP = LB;
6550
6551 IsExpressionFirstInfo = false;
6552 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006553 }
6554 }
6555 }
6556
Samuel Antaod486f842016-05-26 16:53:38 +00006557 /// \brief Return the adjusted map modifiers if the declaration a capture
6558 /// refers to appears in a first-private clause. This is expected to be used
6559 /// only with directives that start with 'target'.
6560 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6561 unsigned CurrentModifiers) {
6562 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6563
6564 // A first private variable captured by reference will use only the
6565 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6566 // declaration is known as first-private in this handler.
6567 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
George Rokos065755d2017-11-07 18:27:04 +00006568 return MappableExprsHandler::OMP_MAP_PRIVATE |
Samuel Antaod486f842016-05-26 16:53:38 +00006569 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006570 // Reduction variable will use only the 'private ptr' and 'map to_from'
6571 // flag.
6572 if (ReductionDecls.count(Cap.getCapturedVar())) {
6573 return MappableExprsHandler::OMP_MAP_TO |
6574 MappableExprsHandler::OMP_MAP_FROM;
6575 }
Samuel Antaod486f842016-05-26 16:53:38 +00006576
6577 // We didn't modify anything.
6578 return CurrentModifiers;
6579 }
6580
Samuel Antao86ace552016-04-27 22:40:57 +00006581public:
6582 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006583 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006584 // Extract firstprivate clause information.
6585 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6586 for (const auto *D : C->varlists())
6587 FirstPrivateDecls.insert(
6588 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006589 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
6590 for (const auto *D : C->varlists()) {
6591 ReductionDecls.insert(
6592 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6593 }
6594 }
Samuel Antao6890b092016-07-28 14:25:09 +00006595 // Extract device pointer clause information.
6596 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6597 for (auto L : C->component_lists())
6598 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006599 }
Samuel Antao86ace552016-04-27 22:40:57 +00006600
6601 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006602 /// types for the extracted mappable expressions. Also, for each item that
6603 /// relates with a device pointer, a pair of the relevant declaration and
6604 /// index where it occurs is appended to the device pointers info array.
6605 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006606 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6607 MapFlagsArrayTy &Types) const {
6608 BasePointers.clear();
6609 Pointers.clear();
6610 Sizes.clear();
6611 Types.clear();
6612
6613 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006614 /// Kind that defines how a device pointer has to be returned.
6615 enum ReturnPointerKind {
6616 // Don't have to return any pointer.
6617 RPK_None,
6618 // Pointer is the base of the declaration.
6619 RPK_Base,
6620 // Pointer is a member of the base declaration - 'this'
6621 RPK_Member,
6622 // Pointer is a reference and a member of the base declaration - 'this'
6623 RPK_MemberReference,
6624 };
Samuel Antao86ace552016-04-27 22:40:57 +00006625 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006626 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6627 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6628 ReturnPointerKind ReturnDevicePointer = RPK_None;
6629 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006630
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006631 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006632 MapInfo(
6633 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6634 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006635 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006636 : Components(Components), MapType(MapType),
6637 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006638 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006639 };
6640
6641 // We have to process the component lists that relate with the same
6642 // declaration in a single chunk so that we can generate the map flags
6643 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006644 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006645
6646 // Helper function to fill the information map for the different supported
6647 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006648 auto &&InfoGen = [&Info](
6649 const ValueDecl *D,
6650 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6651 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006652 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006653 const ValueDecl *VD =
6654 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006655 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6656 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006657 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006658
Paul Robinson78fb1322016-08-01 22:12:46 +00006659 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006660 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006661 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006662 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006663 MapInfo::RPK_None, C->isImplicit());
6664 }
Paul Robinson15c84002016-07-29 20:46:16 +00006665 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006666 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006667 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006668 MapInfo::RPK_None, C->isImplicit());
6669 }
Paul Robinson15c84002016-07-29 20:46:16 +00006670 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006671 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006672 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006673 MapInfo::RPK_None, C->isImplicit());
6674 }
Samuel Antao86ace552016-04-27 22:40:57 +00006675
Samuel Antaocc10b852016-07-28 14:23:26 +00006676 // Look at the use_device_ptr clause information and mark the existing map
6677 // entries as such. If there is no map information for an entry in the
6678 // use_device_ptr list, we create one with map type 'alloc' and zero size
6679 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006680 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006681 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006682 for (auto L : C->component_lists()) {
6683 assert(!L.second.empty() && "Not expecting empty list of components!");
6684 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6685 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6686 auto *IE = L.second.back().getAssociatedExpression();
6687 // If the first component is a member expression, we have to look into
6688 // 'this', which maps to null in the map of map information. Otherwise
6689 // look directly for the information.
6690 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6691
6692 // We potentially have map information for this declaration already.
6693 // Look for the first set of components that refer to it.
6694 if (It != Info.end()) {
6695 auto CI = std::find_if(
6696 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6697 return MI.Components.back().getAssociatedDeclaration() == VD;
6698 });
6699 // If we found a map entry, signal that the pointer has to be returned
6700 // and move on to the next declaration.
6701 if (CI != It->second.end()) {
6702 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6703 ? (VD->getType()->isReferenceType()
6704 ? MapInfo::RPK_MemberReference
6705 : MapInfo::RPK_Member)
6706 : MapInfo::RPK_Base;
6707 continue;
6708 }
6709 }
6710
6711 // We didn't find any match in our map information - generate a zero
6712 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006713 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006714 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006715 this->CGF
6716 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006717 .getScalarVal();
6718 BasePointers.push_back({Ptr, VD});
6719 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006720 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00006721 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00006722 }
6723
Samuel Antao86ace552016-04-27 22:40:57 +00006724 for (auto &M : Info) {
6725 // We need to know when we generate information for the first component
6726 // associated with a capture, because the mapping flags depend on it.
6727 bool IsFirstComponentList = true;
6728 for (MapInfo &L : M.second) {
6729 assert(!L.Components.empty() &&
6730 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006731
6732 // Remember the current base pointer index.
6733 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006734 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006735 this->generateInfoForComponentList(
6736 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6737 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006738
6739 // If this entry relates with a device pointer, set the relevant
6740 // declaration and add the 'return pointer' flag.
6741 if (IsFirstComponentList &&
6742 L.ReturnDevicePointer != MapInfo::RPK_None) {
6743 // If the pointer is not the base of the map, we need to skip the
6744 // base. If it is a reference in a member field, we also need to skip
6745 // the map of the reference.
6746 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6747 ++CurrentBasePointersIdx;
6748 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6749 ++CurrentBasePointersIdx;
6750 }
6751 assert(BasePointers.size() > CurrentBasePointersIdx &&
6752 "Unexpected number of mapped base pointers.");
6753
6754 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6755 assert(RelevantVD &&
6756 "No relevant declaration related with device pointer??");
6757
6758 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00006759 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006760 }
Samuel Antao86ace552016-04-27 22:40:57 +00006761 IsFirstComponentList = false;
6762 }
6763 }
6764 }
6765
6766 /// \brief Generate the base pointers, section pointers, sizes and map types
6767 /// associated to a given capture.
6768 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006769 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006770 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006771 MapValuesArrayTy &Pointers,
6772 MapValuesArrayTy &Sizes,
6773 MapFlagsArrayTy &Types) const {
6774 assert(!Cap->capturesVariableArrayType() &&
6775 "Not expecting to generate map info for a variable array type!");
6776
6777 BasePointers.clear();
6778 Pointers.clear();
6779 Sizes.clear();
6780 Types.clear();
6781
Samuel Antao6890b092016-07-28 14:25:09 +00006782 // We need to know when we generating information for the first component
6783 // associated with a capture, because the mapping flags depend on it.
6784 bool IsFirstComponentList = true;
6785
Samuel Antao86ace552016-04-27 22:40:57 +00006786 const ValueDecl *VD =
6787 Cap->capturesThis()
6788 ? nullptr
6789 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6790
Samuel Antao6890b092016-07-28 14:25:09 +00006791 // If this declaration appears in a is_device_ptr clause we just have to
6792 // pass the pointer by value. If it is a reference to a declaration, we just
6793 // pass its value, otherwise, if it is a member expression, we need to map
6794 // 'to' the field.
6795 if (!VD) {
6796 auto It = DevPointersMap.find(VD);
6797 if (It != DevPointersMap.end()) {
6798 for (auto L : It->second) {
6799 generateInfoForComponentList(
6800 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006801 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6802 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006803 IsFirstComponentList = false;
6804 }
6805 return;
6806 }
6807 } else if (DevPointersMap.count(VD)) {
6808 BasePointers.push_back({Arg, VD});
6809 Pointers.push_back(Arg);
6810 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00006811 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00006812 return;
6813 }
6814
Paul Robinson78fb1322016-08-01 22:12:46 +00006815 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006816 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006817 for (auto L : C->decl_component_lists(VD)) {
6818 assert(L.first == VD &&
6819 "We got information for the wrong declaration??");
6820 assert(!L.second.empty() &&
6821 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006822 generateInfoForComponentList(
6823 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6824 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006825 IsFirstComponentList = false;
6826 }
6827
6828 return;
6829 }
Samuel Antaod486f842016-05-26 16:53:38 +00006830
6831 /// \brief Generate the default map information for a given capture \a CI,
6832 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006833 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6834 const FieldDecl &RI, llvm::Value *CV,
6835 MapBaseValuesArrayTy &CurBasePointers,
6836 MapValuesArrayTy &CurPointers,
6837 MapValuesArrayTy &CurSizes,
6838 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006839
6840 // Do the default mapping.
6841 if (CI.capturesThis()) {
6842 CurBasePointers.push_back(CV);
6843 CurPointers.push_back(CV);
6844 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6845 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6846 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006847 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006848 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006849 CurBasePointers.push_back(CV);
6850 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006851 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006852 // We have to signal to the runtime captures passed by value that are
6853 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00006854 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006855 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6856 } else {
6857 // Pointers are implicitly mapped with a zero size and no flags
6858 // (other than first map that is added for all implicit maps).
6859 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006860 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6861 }
6862 } else {
6863 assert(CI.capturesVariable() && "Expected captured reference.");
6864 CurBasePointers.push_back(CV);
6865 CurPointers.push_back(CV);
6866
6867 const ReferenceType *PtrTy =
6868 cast<ReferenceType>(RI.getType().getTypePtr());
6869 QualType ElementType = PtrTy->getPointeeType();
6870 CurSizes.push_back(CGF.getTypeSize(ElementType));
6871 // The default map type for a scalar/complex type is 'to' because by
6872 // default the value doesn't have to be retrieved. For an aggregate
6873 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006874 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
6875 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
6876 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00006877 }
George Rokos065755d2017-11-07 18:27:04 +00006878 // Every default map produces a single argument which is a target parameter.
6879 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00006880 }
Samuel Antao86ace552016-04-27 22:40:57 +00006881};
Samuel Antaodf158d52016-04-27 22:58:19 +00006882
6883enum OpenMPOffloadingReservedDeviceIDs {
6884 /// \brief Device ID if the device was not defined, runtime should get it
6885 /// from environment variables in the spec.
6886 OMP_DEVICEID_UNDEF = -1,
6887};
6888} // anonymous namespace
6889
6890/// \brief Emit the arrays used to pass the captures and map information to the
6891/// offloading runtime library. If there is no map or capture information,
6892/// return nullptr by reference.
6893static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006894emitOffloadingArrays(CodeGenFunction &CGF,
6895 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006896 MappableExprsHandler::MapValuesArrayTy &Pointers,
6897 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006898 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6899 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006900 auto &CGM = CGF.CGM;
6901 auto &Ctx = CGF.getContext();
6902
Samuel Antaocc10b852016-07-28 14:23:26 +00006903 // Reset the array information.
6904 Info.clearArrayInfo();
6905 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006906
Samuel Antaocc10b852016-07-28 14:23:26 +00006907 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006908 // Detect if we have any capture size requiring runtime evaluation of the
6909 // size so that a constant array could be eventually used.
6910 bool hasRuntimeEvaluationCaptureSize = false;
6911 for (auto *S : Sizes)
6912 if (!isa<llvm::Constant>(S)) {
6913 hasRuntimeEvaluationCaptureSize = true;
6914 break;
6915 }
6916
Samuel Antaocc10b852016-07-28 14:23:26 +00006917 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006918 QualType PointerArrayType =
6919 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6920 /*IndexTypeQuals=*/0);
6921
Samuel Antaocc10b852016-07-28 14:23:26 +00006922 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006923 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006924 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006925 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6926
6927 // If we don't have any VLA types or other types that require runtime
6928 // evaluation, we can use a constant array for the map sizes, otherwise we
6929 // need to fill up the arrays as we do for the pointers.
6930 if (hasRuntimeEvaluationCaptureSize) {
6931 QualType SizeArrayType = Ctx.getConstantArrayType(
6932 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6933 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006934 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006935 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6936 } else {
6937 // We expect all the sizes to be constant, so we collect them to create
6938 // a constant array.
6939 SmallVector<llvm::Constant *, 16> ConstSizes;
6940 for (auto S : Sizes)
6941 ConstSizes.push_back(cast<llvm::Constant>(S));
6942
6943 auto *SizesArrayInit = llvm::ConstantArray::get(
6944 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6945 auto *SizesArrayGbl = new llvm::GlobalVariable(
6946 CGM.getModule(), SizesArrayInit->getType(),
6947 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6948 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006949 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006950 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006951 }
6952
6953 // The map types are always constant so we don't need to generate code to
6954 // fill arrays. Instead, we create an array constant.
6955 llvm::Constant *MapTypesArrayInit =
6956 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6957 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6958 CGM.getModule(), MapTypesArrayInit->getType(),
6959 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6960 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006961 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006962 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006963
Samuel Antaocc10b852016-07-28 14:23:26 +00006964 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6965 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006966 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006967 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6968 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006969 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6970 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006971 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6972 CGF.Builder.CreateStore(BPVal, BPAddr);
6973
Samuel Antaocc10b852016-07-28 14:23:26 +00006974 if (Info.requiresDevicePointerInfo())
6975 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6976 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6977
Samuel Antaodf158d52016-04-27 22:58:19 +00006978 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006979 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006980 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6981 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006982 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6983 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006984 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6985 CGF.Builder.CreateStore(PVal, PAddr);
6986
6987 if (hasRuntimeEvaluationCaptureSize) {
6988 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006989 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6990 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006991 /*Idx0=*/0,
6992 /*Idx1=*/i);
6993 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6994 CGF.Builder.CreateStore(
6995 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6996 SAddr);
6997 }
6998 }
6999 }
7000}
7001/// \brief Emit the arguments to be passed to the runtime library based on the
7002/// arrays of pointers, sizes and map types.
7003static void emitOffloadingArraysArgument(
7004 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7005 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007006 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007007 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007008 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007009 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007010 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7011 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007012 /*Idx0=*/0, /*Idx1=*/0);
7013 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007014 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7015 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007016 /*Idx0=*/0,
7017 /*Idx1=*/0);
7018 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007019 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007020 /*Idx0=*/0, /*Idx1=*/0);
7021 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007022 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007023 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007024 /*Idx0=*/0,
7025 /*Idx1=*/0);
7026 } else {
7027 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7028 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7029 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7030 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007031 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007032 }
Samuel Antao86ace552016-04-27 22:40:57 +00007033}
7034
Samuel Antaobed3c462015-10-02 16:14:20 +00007035void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7036 const OMPExecutableDirective &D,
7037 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007038 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00007039 const Expr *IfCond, const Expr *Device,
7040 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007041 if (!CGF.HaveInsertPoint())
7042 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007043
Samuel Antaoee8fb302016-01-06 13:42:12 +00007044 assert(OutlinedFn && "Invalid outlined function!");
7045
Samuel Antao86ace552016-04-27 22:40:57 +00007046 // Fill up the arrays with all the captured variables.
7047 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00007048 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00007049 MappableExprsHandler::MapValuesArrayTy Pointers;
7050 MappableExprsHandler::MapValuesArrayTy Sizes;
7051 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00007052
Samuel Antaocc10b852016-07-28 14:23:26 +00007053 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00007054 MappableExprsHandler::MapValuesArrayTy CurPointers;
7055 MappableExprsHandler::MapValuesArrayTy CurSizes;
7056 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7057
Samuel Antaod486f842016-05-26 16:53:38 +00007058 // Get mappable expression information.
7059 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00007060
7061 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
7062 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00007063 auto CV = CapturedVars.begin();
7064 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7065 CE = CS.capture_end();
7066 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00007067 CurBasePointers.clear();
7068 CurPointers.clear();
7069 CurSizes.clear();
7070 CurMapTypes.clear();
7071
7072 // VLA sizes are passed to the outlined region by copy and do not have map
7073 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00007074 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00007075 CurBasePointers.push_back(*CV);
7076 CurPointers.push_back(*CV);
7077 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007078 // Copy to the device as an argument. No need to retrieve it.
George Rokos065755d2017-11-07 18:27:04 +00007079 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7080 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
Samuel Antaobed3c462015-10-02 16:14:20 +00007081 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00007082 // If we have any information in the map clause, we use it, otherwise we
7083 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00007084 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007085 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00007086 if (CurBasePointers.empty())
7087 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7088 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00007089 }
Samuel Antao86ace552016-04-27 22:40:57 +00007090 // We expect to have at least an element of information for this capture.
7091 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
7092 assert(CurBasePointers.size() == CurPointers.size() &&
7093 CurBasePointers.size() == CurSizes.size() &&
7094 CurBasePointers.size() == CurMapTypes.size() &&
7095 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007096
Samuel Antao86ace552016-04-27 22:40:57 +00007097 // The kernel args are always the first elements of the base pointers
7098 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00007099 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00007100 // We need to append the results of this capture to what we already have.
7101 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7102 Pointers.append(CurPointers.begin(), CurPointers.end());
7103 Sizes.append(CurSizes.begin(), CurSizes.end());
7104 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00007105 }
7106
Samuel Antaobed3c462015-10-02 16:14:20 +00007107 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007108 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
7109 OutlinedFn, OutlinedFnID, &D,
7110 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007111 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00007112 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007113 TargetDataInfo Info;
7114 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7115 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7116 Info.PointersArray, Info.SizesArray,
7117 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00007118
7119 // On top of the arrays that were filled up, the target offloading call
7120 // takes as arguments the device id as well as the host pointer. The host
7121 // pointer is used by the runtime library to identify the current target
7122 // region, so it only has to be unique and not necessarily point to
7123 // anything. It could be the pointer to the outlined function that
7124 // implements the target region, but we aren't using that so that the
7125 // compiler doesn't need to keep that, and could therefore inline the host
7126 // function if proven worthwhile during optimization.
7127
Samuel Antaoee8fb302016-01-06 13:42:12 +00007128 // From this point on, we need to have an ID of the target region defined.
7129 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007130
7131 // Emit device ID if any.
7132 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007133 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007134 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007135 CGF.Int64Ty, /*isSigned=*/true);
7136 } else {
7137 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7138 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007139
Samuel Antaodf158d52016-04-27 22:58:19 +00007140 // Emit the number of elements in the offloading arrays.
7141 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7142
Samuel Antaob68e2db2016-03-03 16:20:23 +00007143 // Return value of the runtime offloading call.
7144 llvm::Value *Return;
7145
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007146 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
7147 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007148
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007149 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007150 // The target region is an outlined function launched by the runtime
7151 // via calls __tgt_target() or __tgt_target_teams().
7152 //
7153 // __tgt_target() launches a target region with one team and one thread,
7154 // executing a serial region. This master thread may in turn launch
7155 // more threads within its team upon encountering a parallel region,
7156 // however, no additional teams can be launched on the device.
7157 //
7158 // __tgt_target_teams() launches a target region with one or more teams,
7159 // each with one or more threads. This call is required for target
7160 // constructs such as:
7161 // 'target teams'
7162 // 'target' / 'teams'
7163 // 'target teams distribute parallel for'
7164 // 'target parallel'
7165 // and so on.
7166 //
7167 // Note that on the host and CPU targets, the runtime implementation of
7168 // these calls simply call the outlined function without forking threads.
7169 // The outlined functions themselves have runtime calls to
7170 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7171 // the compiler in emitTeamsCall() and emitParallelCall().
7172 //
7173 // In contrast, on the NVPTX target, the implementation of
7174 // __tgt_target_teams() launches a GPU kernel with the requested number
7175 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007176 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007177 // If we have NumTeams defined this means that we have an enclosed teams
7178 // region. Therefore we also expect to have NumThreads defined. These two
7179 // values should be defined in the presence of a teams directive,
7180 // regardless of having any clauses associated. If the user is using teams
7181 // but no clauses, these two values will be the default that should be
7182 // passed to the runtime library - a 32-bit integer with the value zero.
7183 assert(NumThreads && "Thread limit expression should be available along "
7184 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007185 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007186 DeviceID, OutlinedFnID,
7187 PointerNum, Info.BasePointersArray,
7188 Info.PointersArray, Info.SizesArray,
7189 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007190 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007191 Return = CGF.EmitRuntimeCall(
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007192 RT.createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7193 : OMPRTL__tgt_target_teams),
7194 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007195 } else {
7196 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007197 DeviceID, OutlinedFnID,
7198 PointerNum, Info.BasePointersArray,
7199 Info.PointersArray, Info.SizesArray,
7200 Info.MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007201 Return = CGF.EmitRuntimeCall(
7202 RT.createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7203 : OMPRTL__tgt_target),
7204 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007205 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007206
Alexey Bataev2a007e02017-10-02 14:20:58 +00007207 // Check the error code and execute the host version if required.
7208 llvm::BasicBlock *OffloadFailedBlock =
7209 CGF.createBasicBlock("omp_offload.failed");
7210 llvm::BasicBlock *OffloadContBlock =
7211 CGF.createBasicBlock("omp_offload.cont");
7212 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7213 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7214
7215 CGF.EmitBlock(OffloadFailedBlock);
7216 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7217 CGF.EmitBranch(OffloadContBlock);
7218
7219 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007220 };
7221
Samuel Antaoee8fb302016-01-06 13:42:12 +00007222 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007223 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7224 PrePostActionTy &) {
7225 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7226 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007227 };
7228
7229 // If we have a target function ID it means that we need to support
7230 // offloading, otherwise, just execute on the host. We need to execute on host
7231 // regardless of the conditional in the if clause if, e.g., the user do not
7232 // specify target triples.
7233 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007234 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007235 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007236 else {
7237 RegionCodeGenTy ThenRCG(ThenGen);
7238 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007239 }
7240 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007241 RegionCodeGenTy ElseRCG(ElseGen);
7242 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007243 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007244}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007245
7246void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7247 StringRef ParentName) {
7248 if (!S)
7249 return;
7250
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007251 // Codegen OMP target directives that offload compute to the device.
7252 bool requiresDeviceCodegen =
7253 isa<OMPExecutableDirective>(S) &&
7254 isOpenMPTargetExecutionDirective(
7255 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007256
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007257 if (requiresDeviceCodegen) {
7258 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007259 unsigned DeviceID;
7260 unsigned FileID;
7261 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007262 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007263 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007264
7265 // Is this a target region that should not be emitted as an entry point? If
7266 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007267 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7268 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007269 return;
7270
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007271 switch (S->getStmtClass()) {
7272 case Stmt::OMPTargetDirectiveClass:
7273 CodeGenFunction::EmitOMPTargetDeviceFunction(
7274 CGM, ParentName, cast<OMPTargetDirective>(*S));
7275 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007276 case Stmt::OMPTargetParallelDirectiveClass:
7277 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7278 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7279 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007280 case Stmt::OMPTargetTeamsDirectiveClass:
7281 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7282 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7283 break;
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007284 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
7285 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
7286 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(*S));
7287 break;
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007288 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
7289 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
7290 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(*S));
7291 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007292 case Stmt::OMPTargetParallelForDirectiveClass:
7293 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7294 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7295 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007296 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7297 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7298 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7299 break;
Alexey Bataevf8365372017-11-17 17:57:25 +00007300 case Stmt::OMPTargetSimdDirectiveClass:
7301 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7302 CGM, ParentName, cast<OMPTargetSimdDirective>(*S));
7303 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007304 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
7305 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7306 CGM, ParentName,
7307 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
7308 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007309 default:
7310 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7311 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007312 return;
7313 }
7314
7315 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007316 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007317 return;
7318
7319 scanForTargetRegionsFunctions(
7320 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7321 ParentName);
7322 return;
7323 }
7324
7325 // If this is a lambda function, look into its body.
7326 if (auto *L = dyn_cast<LambdaExpr>(S))
7327 S = L->getBody();
7328
7329 // Keep looking for target regions recursively.
7330 for (auto *II : S->children())
7331 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007332}
7333
7334bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7335 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7336
7337 // If emitting code for the host, we do not process FD here. Instead we do
7338 // the normal code generation.
7339 if (!CGM.getLangOpts().OpenMPIsDevice)
7340 return false;
7341
7342 // Try to detect target regions in the function.
7343 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7344
Samuel Antao4b75b872016-12-12 19:26:31 +00007345 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007346 // scanning. Therefore, we signal that this function is completely dealt
7347 // with.
7348 return true;
7349}
7350
7351bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7352 if (!CGM.getLangOpts().OpenMPIsDevice)
7353 return false;
7354
7355 // Check if there are Ctors/Dtors in this declaration and look for target
7356 // regions in it. We use the complete variant to produce the kernel name
7357 // mangling.
7358 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7359 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7360 for (auto *Ctor : RD->ctors()) {
7361 StringRef ParentName =
7362 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7363 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7364 }
7365 auto *Dtor = RD->getDestructor();
7366 if (Dtor) {
7367 StringRef ParentName =
7368 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7369 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7370 }
7371 }
7372
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007373 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007374 // implemented yet). Therefore we signal that GD was processed in this case.
7375 return true;
7376}
7377
7378bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7379 auto *VD = GD.getDecl();
7380 if (isa<FunctionDecl>(VD))
7381 return emitTargetFunctions(GD);
7382
7383 return emitTargetGlobalVariable(GD);
7384}
7385
7386llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7387 // If we have offloading in the current module, we need to emit the entries
7388 // now and register the offloading descriptor.
7389 createOffloadEntriesAndInfoMetadata();
7390
7391 // Create and register the offloading binary descriptors. This is the main
7392 // entity that captures all the information about offloading in the current
7393 // compilation unit.
7394 return createOffloadingBinaryDescriptorRegistration();
7395}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007396
7397void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7398 const OMPExecutableDirective &D,
7399 SourceLocation Loc,
7400 llvm::Value *OutlinedFn,
7401 ArrayRef<llvm::Value *> CapturedVars) {
7402 if (!CGF.HaveInsertPoint())
7403 return;
7404
7405 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7406 CodeGenFunction::RunCleanupsScope Scope(CGF);
7407
7408 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7409 llvm::Value *Args[] = {
7410 RTLoc,
7411 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7412 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7413 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7414 RealArgs.append(std::begin(Args), std::end(Args));
7415 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7416
7417 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7418 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7419}
7420
7421void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007422 const Expr *NumTeams,
7423 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007424 SourceLocation Loc) {
7425 if (!CGF.HaveInsertPoint())
7426 return;
7427
7428 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7429
Carlo Bertollic6872252016-04-04 15:55:02 +00007430 llvm::Value *NumTeamsVal =
7431 (NumTeams)
7432 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7433 CGF.CGM.Int32Ty, /* isSigned = */ true)
7434 : CGF.Builder.getInt32(0);
7435
7436 llvm::Value *ThreadLimitVal =
7437 (ThreadLimit)
7438 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7439 CGF.CGM.Int32Ty, /* isSigned = */ true)
7440 : CGF.Builder.getInt32(0);
7441
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007442 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007443 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7444 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007445 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7446 PushNumTeamsArgs);
7447}
Samuel Antaodf158d52016-04-27 22:58:19 +00007448
Samuel Antaocc10b852016-07-28 14:23:26 +00007449void CGOpenMPRuntime::emitTargetDataCalls(
7450 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7451 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007452 if (!CGF.HaveInsertPoint())
7453 return;
7454
Samuel Antaocc10b852016-07-28 14:23:26 +00007455 // Action used to replace the default codegen action and turn privatization
7456 // off.
7457 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007458
7459 // Generate the code for the opening of the data environment. Capture all the
7460 // arguments of the runtime call by reference because they are used in the
7461 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007462 auto &&BeginThenGen = [this, &D, Device, &Info,
7463 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007464 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007465 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007466 MappableExprsHandler::MapValuesArrayTy Pointers;
7467 MappableExprsHandler::MapValuesArrayTy Sizes;
7468 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7469
7470 // Get map clause information.
7471 MappableExprsHandler MCHandler(D, CGF);
7472 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007473
7474 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007475 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007476
7477 llvm::Value *BasePointersArrayArg = nullptr;
7478 llvm::Value *PointersArrayArg = nullptr;
7479 llvm::Value *SizesArrayArg = nullptr;
7480 llvm::Value *MapTypesArrayArg = nullptr;
7481 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007482 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007483
7484 // Emit device ID if any.
7485 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007486 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007487 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007488 CGF.Int64Ty, /*isSigned=*/true);
7489 } else {
7490 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7491 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007492
7493 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007494 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007495
7496 llvm::Value *OffloadingArgs[] = {
7497 DeviceID, PointerNum, BasePointersArrayArg,
7498 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007499 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00007500 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007501
7502 // If device pointer privatization is required, emit the body of the region
7503 // here. It will have to be duplicated: with and without privatization.
7504 if (!Info.CaptureDeviceAddrMap.empty())
7505 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007506 };
7507
7508 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007509 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
7510 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007511 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007512
7513 llvm::Value *BasePointersArrayArg = nullptr;
7514 llvm::Value *PointersArrayArg = nullptr;
7515 llvm::Value *SizesArrayArg = nullptr;
7516 llvm::Value *MapTypesArrayArg = nullptr;
7517 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007518 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007519
7520 // Emit device ID if any.
7521 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007522 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007523 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007524 CGF.Int64Ty, /*isSigned=*/true);
7525 } else {
7526 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7527 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007528
7529 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007530 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007531
7532 llvm::Value *OffloadingArgs[] = {
7533 DeviceID, PointerNum, BasePointersArrayArg,
7534 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007535 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00007536 OffloadingArgs);
7537 };
7538
Samuel Antaocc10b852016-07-28 14:23:26 +00007539 // If we need device pointer privatization, we need to emit the body of the
7540 // region with no privatization in the 'else' branch of the conditional.
7541 // Otherwise, we don't have to do anything.
7542 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7543 PrePostActionTy &) {
7544 if (!Info.CaptureDeviceAddrMap.empty()) {
7545 CodeGen.setAction(NoPrivAction);
7546 CodeGen(CGF);
7547 }
7548 };
7549
7550 // We don't have to do anything to close the region if the if clause evaluates
7551 // to false.
7552 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007553
7554 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007555 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007556 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007557 RegionCodeGenTy RCG(BeginThenGen);
7558 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007559 }
7560
Samuel Antaocc10b852016-07-28 14:23:26 +00007561 // If we don't require privatization of device pointers, we emit the body in
7562 // between the runtime calls. This avoids duplicating the body code.
7563 if (Info.CaptureDeviceAddrMap.empty()) {
7564 CodeGen.setAction(NoPrivAction);
7565 CodeGen(CGF);
7566 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007567
7568 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007569 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007570 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007571 RegionCodeGenTy RCG(EndThenGen);
7572 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007573 }
7574}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007575
Samuel Antao8d2d7302016-05-26 18:30:22 +00007576void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007577 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7578 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007579 if (!CGF.HaveInsertPoint())
7580 return;
7581
Samuel Antao8dd66282016-04-27 23:14:30 +00007582 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007583 isa<OMPTargetExitDataDirective>(D) ||
7584 isa<OMPTargetUpdateDirective>(D)) &&
7585 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007586
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007587 CodeGenFunction::OMPTargetDataInfo InputInfo;
7588 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007589 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007590 auto &&ThenGen = [this, &D, Device, &InputInfo,
7591 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007592 // Emit device ID if any.
7593 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007594 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007595 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007596 CGF.Int64Ty, /*isSigned=*/true);
7597 } else {
7598 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7599 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007600
7601 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007602 llvm::Constant *PointerNum =
7603 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007604
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007605 llvm::Value *OffloadingArgs[] = {DeviceID,
7606 PointerNum,
7607 InputInfo.BasePointersArray.getPointer(),
7608 InputInfo.PointersArray.getPointer(),
7609 InputInfo.SizesArray.getPointer(),
7610 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007611
Samuel Antao8d2d7302016-05-26 18:30:22 +00007612 // Select the right runtime function call for each expected standalone
7613 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007614 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007615 OpenMPRTLFunction RTLFn;
7616 switch (D.getDirectiveKind()) {
7617 default:
7618 llvm_unreachable("Unexpected standalone target data directive.");
7619 break;
7620 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007621 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
7622 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007623 break;
7624 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007625 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
7626 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007627 break;
7628 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007629 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
7630 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007631 break;
7632 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007633 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007634 };
7635
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007636 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
7637 CodeGenFunction &CGF, PrePostActionTy &) {
7638 // Fill up the arrays with all the mapped variables.
7639 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7640 MappableExprsHandler::MapValuesArrayTy Pointers;
7641 MappableExprsHandler::MapValuesArrayTy Sizes;
7642 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007643
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007644 // Get map clause information.
7645 MappableExprsHandler MEHandler(D, CGF);
7646 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
7647
7648 TargetDataInfo Info;
7649 // Fill up the arrays and create the arguments.
7650 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7651 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7652 Info.PointersArray, Info.SizesArray,
7653 Info.MapTypesArray, Info);
7654 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7655 InputInfo.BasePointersArray =
7656 Address(Info.BasePointersArray, CGM.getPointerAlign());
7657 InputInfo.PointersArray =
7658 Address(Info.PointersArray, CGM.getPointerAlign());
7659 InputInfo.SizesArray =
7660 Address(Info.SizesArray, CGM.getPointerAlign());
7661 MapTypesArray = Info.MapTypesArray;
7662 if (D.hasClausesOfKind<OMPDependClause>())
7663 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7664 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00007665 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007666 };
7667
7668 if (IfCond)
7669 emitOMPIfClause(CGF, IfCond, TargetThenGen,
7670 [](CodeGenFunction &CGF, PrePostActionTy &) {});
7671 else {
7672 RegionCodeGenTy ThenRCG(TargetThenGen);
7673 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007674 }
7675}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007676
7677namespace {
7678 /// Kind of parameter in a function with 'declare simd' directive.
7679 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7680 /// Attribute set of the parameter.
7681 struct ParamAttrTy {
7682 ParamKindTy Kind = Vector;
7683 llvm::APSInt StrideOrArg;
7684 llvm::APSInt Alignment;
7685 };
7686} // namespace
7687
7688static unsigned evaluateCDTSize(const FunctionDecl *FD,
7689 ArrayRef<ParamAttrTy> ParamAttrs) {
7690 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7691 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7692 // of that clause. The VLEN value must be power of 2.
7693 // In other case the notion of the function`s "characteristic data type" (CDT)
7694 // is used to compute the vector length.
7695 // CDT is defined in the following order:
7696 // a) For non-void function, the CDT is the return type.
7697 // b) If the function has any non-uniform, non-linear parameters, then the
7698 // CDT is the type of the first such parameter.
7699 // c) If the CDT determined by a) or b) above is struct, union, or class
7700 // type which is pass-by-value (except for the type that maps to the
7701 // built-in complex data type), the characteristic data type is int.
7702 // d) If none of the above three cases is applicable, the CDT is int.
7703 // The VLEN is then determined based on the CDT and the size of vector
7704 // register of that ISA for which current vector version is generated. The
7705 // VLEN is computed using the formula below:
7706 // VLEN = sizeof(vector_register) / sizeof(CDT),
7707 // where vector register size specified in section 3.2.1 Registers and the
7708 // Stack Frame of original AMD64 ABI document.
7709 QualType RetType = FD->getReturnType();
7710 if (RetType.isNull())
7711 return 0;
7712 ASTContext &C = FD->getASTContext();
7713 QualType CDT;
7714 if (!RetType.isNull() && !RetType->isVoidType())
7715 CDT = RetType;
7716 else {
7717 unsigned Offset = 0;
7718 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7719 if (ParamAttrs[Offset].Kind == Vector)
7720 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7721 ++Offset;
7722 }
7723 if (CDT.isNull()) {
7724 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7725 if (ParamAttrs[I + Offset].Kind == Vector) {
7726 CDT = FD->getParamDecl(I)->getType();
7727 break;
7728 }
7729 }
7730 }
7731 }
7732 if (CDT.isNull())
7733 CDT = C.IntTy;
7734 CDT = CDT->getCanonicalTypeUnqualified();
7735 if (CDT->isRecordType() || CDT->isUnionType())
7736 CDT = C.IntTy;
7737 return C.getTypeSize(CDT);
7738}
7739
7740static void
7741emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007742 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007743 ArrayRef<ParamAttrTy> ParamAttrs,
7744 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7745 struct ISADataTy {
7746 char ISA;
7747 unsigned VecRegSize;
7748 };
7749 ISADataTy ISAData[] = {
7750 {
7751 'b', 128
7752 }, // SSE
7753 {
7754 'c', 256
7755 }, // AVX
7756 {
7757 'd', 256
7758 }, // AVX2
7759 {
7760 'e', 512
7761 }, // AVX512
7762 };
7763 llvm::SmallVector<char, 2> Masked;
7764 switch (State) {
7765 case OMPDeclareSimdDeclAttr::BS_Undefined:
7766 Masked.push_back('N');
7767 Masked.push_back('M');
7768 break;
7769 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7770 Masked.push_back('N');
7771 break;
7772 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7773 Masked.push_back('M');
7774 break;
7775 }
7776 for (auto Mask : Masked) {
7777 for (auto &Data : ISAData) {
7778 SmallString<256> Buffer;
7779 llvm::raw_svector_ostream Out(Buffer);
7780 Out << "_ZGV" << Data.ISA << Mask;
7781 if (!VLENVal) {
7782 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7783 evaluateCDTSize(FD, ParamAttrs));
7784 } else
7785 Out << VLENVal;
7786 for (auto &ParamAttr : ParamAttrs) {
7787 switch (ParamAttr.Kind){
7788 case LinearWithVarStride:
7789 Out << 's' << ParamAttr.StrideOrArg;
7790 break;
7791 case Linear:
7792 Out << 'l';
7793 if (!!ParamAttr.StrideOrArg)
7794 Out << ParamAttr.StrideOrArg;
7795 break;
7796 case Uniform:
7797 Out << 'u';
7798 break;
7799 case Vector:
7800 Out << 'v';
7801 break;
7802 }
7803 if (!!ParamAttr.Alignment)
7804 Out << 'a' << ParamAttr.Alignment;
7805 }
7806 Out << '_' << Fn->getName();
7807 Fn->addFnAttr(Out.str());
7808 }
7809 }
7810}
7811
7812void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7813 llvm::Function *Fn) {
7814 ASTContext &C = CGM.getContext();
7815 FD = FD->getCanonicalDecl();
7816 // Map params to their positions in function decl.
7817 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7818 if (isa<CXXMethodDecl>(FD))
7819 ParamPositions.insert({FD, 0});
7820 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007821 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007822 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7823 ++ParamPos;
7824 }
7825 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7826 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7827 // Mark uniform parameters.
7828 for (auto *E : Attr->uniforms()) {
7829 E = E->IgnoreParenImpCasts();
7830 unsigned Pos;
7831 if (isa<CXXThisExpr>(E))
7832 Pos = ParamPositions[FD];
7833 else {
7834 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7835 ->getCanonicalDecl();
7836 Pos = ParamPositions[PVD];
7837 }
7838 ParamAttrs[Pos].Kind = Uniform;
7839 }
7840 // Get alignment info.
7841 auto NI = Attr->alignments_begin();
7842 for (auto *E : Attr->aligneds()) {
7843 E = E->IgnoreParenImpCasts();
7844 unsigned Pos;
7845 QualType ParmTy;
7846 if (isa<CXXThisExpr>(E)) {
7847 Pos = ParamPositions[FD];
7848 ParmTy = E->getType();
7849 } else {
7850 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7851 ->getCanonicalDecl();
7852 Pos = ParamPositions[PVD];
7853 ParmTy = PVD->getType();
7854 }
7855 ParamAttrs[Pos].Alignment =
7856 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7857 : llvm::APSInt::getUnsigned(
7858 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7859 .getQuantity());
7860 ++NI;
7861 }
7862 // Mark linear parameters.
7863 auto SI = Attr->steps_begin();
7864 auto MI = Attr->modifiers_begin();
7865 for (auto *E : Attr->linears()) {
7866 E = E->IgnoreParenImpCasts();
7867 unsigned Pos;
7868 if (isa<CXXThisExpr>(E))
7869 Pos = ParamPositions[FD];
7870 else {
7871 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7872 ->getCanonicalDecl();
7873 Pos = ParamPositions[PVD];
7874 }
7875 auto &ParamAttr = ParamAttrs[Pos];
7876 ParamAttr.Kind = Linear;
7877 if (*SI) {
7878 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7879 Expr::SE_AllowSideEffects)) {
7880 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7881 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7882 ParamAttr.Kind = LinearWithVarStride;
7883 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7884 ParamPositions[StridePVD->getCanonicalDecl()]);
7885 }
7886 }
7887 }
7888 }
7889 ++SI;
7890 ++MI;
7891 }
7892 llvm::APSInt VLENVal;
7893 if (const Expr *VLEN = Attr->getSimdlen())
7894 VLENVal = VLEN->EvaluateKnownConstInt(C);
7895 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7896 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7897 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7898 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7899 }
7900}
Alexey Bataev8b427062016-05-25 12:36:08 +00007901
7902namespace {
7903/// Cleanup action for doacross support.
7904class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7905public:
7906 static const int DoacrossFinArgs = 2;
7907
7908private:
7909 llvm::Value *RTLFn;
7910 llvm::Value *Args[DoacrossFinArgs];
7911
7912public:
7913 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7914 : RTLFn(RTLFn) {
7915 assert(CallArgs.size() == DoacrossFinArgs);
7916 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7917 }
7918 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7919 if (!CGF.HaveInsertPoint())
7920 return;
7921 CGF.EmitRuntimeCall(RTLFn, Args);
7922 }
7923};
7924} // namespace
7925
7926void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7927 const OMPLoopDirective &D) {
7928 if (!CGF.HaveInsertPoint())
7929 return;
7930
7931 ASTContext &C = CGM.getContext();
7932 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7933 RecordDecl *RD;
7934 if (KmpDimTy.isNull()) {
7935 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7936 // kmp_int64 lo; // lower
7937 // kmp_int64 up; // upper
7938 // kmp_int64 st; // stride
7939 // };
7940 RD = C.buildImplicitRecord("kmp_dim");
7941 RD->startDefinition();
7942 addFieldToRecordDecl(C, RD, Int64Ty);
7943 addFieldToRecordDecl(C, RD, Int64Ty);
7944 addFieldToRecordDecl(C, RD, Int64Ty);
7945 RD->completeDefinition();
7946 KmpDimTy = C.getRecordType(RD);
7947 } else
7948 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7949
7950 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7951 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7952 enum { LowerFD = 0, UpperFD, StrideFD };
7953 // Fill dims with data.
7954 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7955 // dims.upper = num_iterations;
7956 LValue UpperLVal =
7957 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7958 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7959 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7960 Int64Ty, D.getNumIterations()->getExprLoc());
7961 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7962 // dims.stride = 1;
7963 LValue StrideLVal =
7964 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7965 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7966 StrideLVal);
7967
7968 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7969 // kmp_int32 num_dims, struct kmp_dim * dims);
7970 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7971 getThreadID(CGF, D.getLocStart()),
7972 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7973 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7974 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7975
7976 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7977 CGF.EmitRuntimeCall(RTLFn, Args);
7978 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7979 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7980 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7981 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7982 llvm::makeArrayRef(FiniArgs));
7983}
7984
7985void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7986 const OMPDependClause *C) {
7987 QualType Int64Ty =
7988 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7989 const Expr *CounterVal = C->getCounterValue();
7990 assert(CounterVal);
7991 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7992 CounterVal->getType(), Int64Ty,
7993 CounterVal->getExprLoc());
7994 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7995 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7996 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7997 getThreadID(CGF, C->getLocStart()),
7998 CntAddr.getPointer()};
7999 llvm::Value *RTLFn;
8000 if (C->getDependencyKind() == OMPC_DEPEND_source)
8001 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
8002 else {
8003 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8004 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8005 }
8006 CGF.EmitRuntimeCall(RTLFn, Args);
8007}
8008
Alexey Bataev3c595a62017-08-14 15:01:03 +00008009void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
8010 ArrayRef<llvm::Value *> Args,
8011 SourceLocation Loc) const {
8012 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8013
8014 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008015 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008016 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008017 return;
8018 }
8019 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008020 CGF.EmitRuntimeCall(Callee, Args);
8021}
8022
8023void CGOpenMPRuntime::emitOutlinedFunctionCall(
8024 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8025 ArrayRef<llvm::Value *> Args) const {
8026 assert(Loc.isValid() && "Outlined function call location must be valid.");
8027 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008028}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008029
8030Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8031 const VarDecl *NativeParam,
8032 const VarDecl *TargetParam) const {
8033 return CGF.GetAddrOfLocalVar(NativeParam);
8034}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008035
8036llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8037 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8038 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8039 llvm_unreachable("Not supported in SIMD-only mode");
8040}
8041
8042llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8043 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8044 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8045 llvm_unreachable("Not supported in SIMD-only mode");
8046}
8047
8048llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8049 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8050 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8051 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8052 bool Tied, unsigned &NumberOfParts) {
8053 llvm_unreachable("Not supported in SIMD-only mode");
8054}
8055
8056void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8057 SourceLocation Loc,
8058 llvm::Value *OutlinedFn,
8059 ArrayRef<llvm::Value *> CapturedVars,
8060 const Expr *IfCond) {
8061 llvm_unreachable("Not supported in SIMD-only mode");
8062}
8063
8064void CGOpenMPSIMDRuntime::emitCriticalRegion(
8065 CodeGenFunction &CGF, StringRef CriticalName,
8066 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8067 const Expr *Hint) {
8068 llvm_unreachable("Not supported in SIMD-only mode");
8069}
8070
8071void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8072 const RegionCodeGenTy &MasterOpGen,
8073 SourceLocation Loc) {
8074 llvm_unreachable("Not supported in SIMD-only mode");
8075}
8076
8077void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8078 SourceLocation Loc) {
8079 llvm_unreachable("Not supported in SIMD-only mode");
8080}
8081
8082void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8083 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8084 SourceLocation Loc) {
8085 llvm_unreachable("Not supported in SIMD-only mode");
8086}
8087
8088void CGOpenMPSIMDRuntime::emitSingleRegion(
8089 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8090 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8091 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8092 ArrayRef<const Expr *> AssignmentOps) {
8093 llvm_unreachable("Not supported in SIMD-only mode");
8094}
8095
8096void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8097 const RegionCodeGenTy &OrderedOpGen,
8098 SourceLocation Loc,
8099 bool IsThreads) {
8100 llvm_unreachable("Not supported in SIMD-only mode");
8101}
8102
8103void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8104 SourceLocation Loc,
8105 OpenMPDirectiveKind Kind,
8106 bool EmitChecks,
8107 bool ForceSimpleCall) {
8108 llvm_unreachable("Not supported in SIMD-only mode");
8109}
8110
8111void CGOpenMPSIMDRuntime::emitForDispatchInit(
8112 CodeGenFunction &CGF, SourceLocation Loc,
8113 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8114 bool Ordered, const DispatchRTInput &DispatchValues) {
8115 llvm_unreachable("Not supported in SIMD-only mode");
8116}
8117
8118void CGOpenMPSIMDRuntime::emitForStaticInit(
8119 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8120 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8121 llvm_unreachable("Not supported in SIMD-only mode");
8122}
8123
8124void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8125 CodeGenFunction &CGF, SourceLocation Loc,
8126 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8127 llvm_unreachable("Not supported in SIMD-only mode");
8128}
8129
8130void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8131 SourceLocation Loc,
8132 unsigned IVSize,
8133 bool IVSigned) {
8134 llvm_unreachable("Not supported in SIMD-only mode");
8135}
8136
8137void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8138 SourceLocation Loc,
8139 OpenMPDirectiveKind DKind) {
8140 llvm_unreachable("Not supported in SIMD-only mode");
8141}
8142
8143llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8144 SourceLocation Loc,
8145 unsigned IVSize, bool IVSigned,
8146 Address IL, Address LB,
8147 Address UB, Address ST) {
8148 llvm_unreachable("Not supported in SIMD-only mode");
8149}
8150
8151void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8152 llvm::Value *NumThreads,
8153 SourceLocation Loc) {
8154 llvm_unreachable("Not supported in SIMD-only mode");
8155}
8156
8157void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8158 OpenMPProcBindClauseKind ProcBind,
8159 SourceLocation Loc) {
8160 llvm_unreachable("Not supported in SIMD-only mode");
8161}
8162
8163Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8164 const VarDecl *VD,
8165 Address VDAddr,
8166 SourceLocation Loc) {
8167 llvm_unreachable("Not supported in SIMD-only mode");
8168}
8169
8170llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8171 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8172 CodeGenFunction *CGF) {
8173 llvm_unreachable("Not supported in SIMD-only mode");
8174}
8175
8176Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8177 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8178 llvm_unreachable("Not supported in SIMD-only mode");
8179}
8180
8181void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8182 ArrayRef<const Expr *> Vars,
8183 SourceLocation Loc) {
8184 llvm_unreachable("Not supported in SIMD-only mode");
8185}
8186
8187void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8188 const OMPExecutableDirective &D,
8189 llvm::Value *TaskFunction,
8190 QualType SharedsTy, Address Shareds,
8191 const Expr *IfCond,
8192 const OMPTaskDataTy &Data) {
8193 llvm_unreachable("Not supported in SIMD-only mode");
8194}
8195
8196void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8197 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8198 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8199 const Expr *IfCond, const OMPTaskDataTy &Data) {
8200 llvm_unreachable("Not supported in SIMD-only mode");
8201}
8202
8203void CGOpenMPSIMDRuntime::emitReduction(
8204 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8205 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8206 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8207 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8208 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8209 ReductionOps, Options);
8210}
8211
8212llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8213 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8214 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8215 llvm_unreachable("Not supported in SIMD-only mode");
8216}
8217
8218void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8219 SourceLocation Loc,
8220 ReductionCodeGen &RCG,
8221 unsigned N) {
8222 llvm_unreachable("Not supported in SIMD-only mode");
8223}
8224
8225Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8226 SourceLocation Loc,
8227 llvm::Value *ReductionsPtr,
8228 LValue SharedLVal) {
8229 llvm_unreachable("Not supported in SIMD-only mode");
8230}
8231
8232void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8233 SourceLocation Loc) {
8234 llvm_unreachable("Not supported in SIMD-only mode");
8235}
8236
8237void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8238 CodeGenFunction &CGF, SourceLocation Loc,
8239 OpenMPDirectiveKind CancelRegion) {
8240 llvm_unreachable("Not supported in SIMD-only mode");
8241}
8242
8243void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8244 SourceLocation Loc, const Expr *IfCond,
8245 OpenMPDirectiveKind CancelRegion) {
8246 llvm_unreachable("Not supported in SIMD-only mode");
8247}
8248
8249void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8250 const OMPExecutableDirective &D, StringRef ParentName,
8251 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8252 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8253 llvm_unreachable("Not supported in SIMD-only mode");
8254}
8255
8256void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8257 const OMPExecutableDirective &D,
8258 llvm::Value *OutlinedFn,
8259 llvm::Value *OutlinedFnID,
8260 const Expr *IfCond, const Expr *Device,
8261 ArrayRef<llvm::Value *> CapturedVars) {
8262 llvm_unreachable("Not supported in SIMD-only mode");
8263}
8264
8265bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8266 llvm_unreachable("Not supported in SIMD-only mode");
8267}
8268
8269bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8270 llvm_unreachable("Not supported in SIMD-only mode");
8271}
8272
8273bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8274 return false;
8275}
8276
8277llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8278 return nullptr;
8279}
8280
8281void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8282 const OMPExecutableDirective &D,
8283 SourceLocation Loc,
8284 llvm::Value *OutlinedFn,
8285 ArrayRef<llvm::Value *> CapturedVars) {
8286 llvm_unreachable("Not supported in SIMD-only mode");
8287}
8288
8289void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8290 const Expr *NumTeams,
8291 const Expr *ThreadLimit,
8292 SourceLocation Loc) {
8293 llvm_unreachable("Not supported in SIMD-only mode");
8294}
8295
8296void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8297 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8298 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8299 llvm_unreachable("Not supported in SIMD-only mode");
8300}
8301
8302void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8303 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8304 const Expr *Device) {
8305 llvm_unreachable("Not supported in SIMD-only mode");
8306}
8307
8308void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8309 const OMPLoopDirective &D) {
8310 llvm_unreachable("Not supported in SIMD-only mode");
8311}
8312
8313void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8314 const OMPDependClause *C) {
8315 llvm_unreachable("Not supported in SIMD-only mode");
8316}
8317
8318const VarDecl *
8319CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8320 const VarDecl *NativeParam) const {
8321 llvm_unreachable("Not supported in SIMD-only mode");
8322}
8323
8324Address
8325CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8326 const VarDecl *NativeParam,
8327 const VarDecl *TargetParam) const {
8328 llvm_unreachable("Not supported in SIMD-only mode");
8329}
8330