blob: 87097cc2cabfdac693fc44a1de311d3bf1fcb679 [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>());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
Alexey Bataev48591dd2016-04-20 04:01:36 +0000151 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,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000357 C.getLocation());
Samuel Antaob68e2db2016-03-03 16:20:23 +0000358 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:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000790 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000791 break;
792 case TEK_Complex:
793 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Aggregate:
797 InitRVal = RValue::getAggregate(LV.getAddress());
798 break;
799 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000800 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000801 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());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001212 CGM.SetInternalFunctionAttributes(GlobalDecl(), 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");
Alexey Bataev475a7442018-01-12 19:39:11 +00001374 const OpenMPDirectiveKind Region =
1375 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1376 : OMPD_task;
1377 auto *CS = D.getCapturedStmt(Region);
Alexey Bataev7292c292016-04-25 12:22:29 +00001378 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001379 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001380 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1381 InnermostKind,
1382 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001383 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001384 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1385 if (!Tied)
1386 NumberOfParts = Action.getNumberOfParts();
1387 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001388}
1389
Alexey Bataev50b3c952016-02-19 10:38:26 +00001390Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001391 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001392 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001393 if (!Entry) {
1394 if (!DefaultOpenMPPSource) {
1395 // Initialize default location for psource field of ident_t structure of
1396 // all ident_t objects. Format is ";file;function;line;column;;".
1397 // Taken from
1398 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1399 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001400 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001401 DefaultOpenMPPSource =
1402 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1403 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001404
John McCall23c9dc62016-11-28 22:18:27 +00001405 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001406 auto fields = builder.beginStruct(IdentTy);
1407 fields.addInt(CGM.Int32Ty, 0);
1408 fields.addInt(CGM.Int32Ty, Flags);
1409 fields.addInt(CGM.Int32Ty, 0);
1410 fields.addInt(CGM.Int32Ty, 0);
1411 fields.add(DefaultOpenMPPSource);
1412 auto DefaultOpenMPLocation =
1413 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1414 llvm::GlobalValue::PrivateLinkage);
1415 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1416
John McCall7f416cc2015-09-08 08:05:57 +00001417 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001418 }
John McCall7f416cc2015-09-08 08:05:57 +00001419 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001420}
1421
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001422llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1423 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001424 unsigned Flags) {
1425 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001426 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001427 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001428 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001429 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001430
1431 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1432
John McCall7f416cc2015-09-08 08:05:57 +00001433 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001434 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1435 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001436 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1437
Alexander Musmanc6388682014-12-15 07:07:06 +00001438 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1439 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001440 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001441 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001442 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1443 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001444 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001445 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001446 LocValue = AI;
1447
1448 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1449 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001450 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001451 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001452 }
1453
1454 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001455 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001456
Alexey Bataevf002aca2014-05-30 05:48:40 +00001457 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1458 if (OMPDebugLoc == nullptr) {
1459 SmallString<128> Buffer2;
1460 llvm::raw_svector_ostream OS2(Buffer2);
1461 // Build debug location
1462 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1463 OS2 << ";" << PLoc.getFilename() << ";";
1464 if (const FunctionDecl *FD =
1465 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1466 OS2 << FD->getQualifiedNameAsString();
1467 }
1468 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1469 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1470 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001471 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001472 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001473 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1474
John McCall7f416cc2015-09-08 08:05:57 +00001475 // Our callers always pass this to a runtime function, so for
1476 // convenience, go ahead and return a naked pointer.
1477 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001478}
1479
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001480llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1481 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001482 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1483
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001484 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001485 // Check whether we've already cached a load of the thread id in this
1486 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001487 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001488 if (I != OpenMPLocThreadIDMap.end()) {
1489 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001490 if (ThreadID != nullptr)
1491 return ThreadID;
1492 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001493 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001494 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1495 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001496 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001497 if (auto *OMPRegionInfo =
1498 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1499 if (OMPRegionInfo->getThreadIDVariable()) {
1500 // Check if this an outlined function with thread id passed as argument.
1501 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001502 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001503 // If value loaded in entry block, cache it and use it everywhere in
1504 // function.
1505 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1506 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1507 Elem.second.ThreadID = ThreadID;
1508 }
1509 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001510 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001511 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001512 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001513
1514 // This is not an outlined function region - need to call __kmpc_int32
1515 // kmpc_global_thread_num(ident_t *loc).
1516 // Generate thread id value and cache this value for use across the
1517 // function.
1518 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1519 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001520 auto *Call = CGF.Builder.CreateCall(
1521 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1522 emitUpdateLocation(CGF, Loc));
1523 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001524 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001525 Elem.second.ThreadID = Call;
1526 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001527}
1528
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001529void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001530 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001531 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1532 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001533 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1534 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1535 UDRMap.erase(D);
1536 }
1537 FunctionUDRMap.erase(CGF.CurFn);
1538 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001539}
1540
1541llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001542 if (!IdentTy) {
1543 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001544 return llvm::PointerType::getUnqual(IdentTy);
1545}
1546
1547llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001548 if (!Kmpc_MicroTy) {
1549 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1550 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1551 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1552 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1553 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001554 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1555}
1556
1557llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001558CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001559 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001560 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001561 case OMPRTL__kmpc_fork_call: {
1562 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1563 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001564 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1565 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001566 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001567 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001568 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1569 break;
1570 }
1571 case OMPRTL__kmpc_global_thread_num: {
1572 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001573 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001574 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001575 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001576 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1577 break;
1578 }
Alexey Bataev97720002014-11-11 04:05:39 +00001579 case OMPRTL__kmpc_threadprivate_cached: {
1580 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1581 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1582 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1583 CGM.VoidPtrTy, CGM.SizeTy,
1584 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1585 llvm::FunctionType *FnTy =
1586 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1588 break;
1589 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001590 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001591 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1592 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001593 llvm::Type *TypeParams[] = {
1594 getIdentTyPointerTy(), CGM.Int32Ty,
1595 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1596 llvm::FunctionType *FnTy =
1597 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1599 break;
1600 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001601 case OMPRTL__kmpc_critical_with_hint: {
1602 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1603 // kmp_critical_name *crit, uintptr_t hint);
1604 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1605 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1606 CGM.IntPtrTy};
1607 llvm::FunctionType *FnTy =
1608 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1609 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1610 break;
1611 }
Alexey Bataev97720002014-11-11 04:05:39 +00001612 case OMPRTL__kmpc_threadprivate_register: {
1613 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1614 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1615 // typedef void *(*kmpc_ctor)(void *);
1616 auto KmpcCtorTy =
1617 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1618 /*isVarArg*/ false)->getPointerTo();
1619 // typedef void *(*kmpc_cctor)(void *, void *);
1620 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1621 auto KmpcCopyCtorTy =
1622 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1623 /*isVarArg*/ false)->getPointerTo();
1624 // typedef void (*kmpc_dtor)(void *);
1625 auto KmpcDtorTy =
1626 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1627 ->getPointerTo();
1628 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1629 KmpcCopyCtorTy, KmpcDtorTy};
1630 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1631 /*isVarArg*/ false);
1632 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1633 break;
1634 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001635 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001636 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1637 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001638 llvm::Type *TypeParams[] = {
1639 getIdentTyPointerTy(), CGM.Int32Ty,
1640 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1641 llvm::FunctionType *FnTy =
1642 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1643 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1644 break;
1645 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001646 case OMPRTL__kmpc_cancel_barrier: {
1647 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1648 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1650 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001651 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1652 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001653 break;
1654 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001655 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001656 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001657 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1658 llvm::FunctionType *FnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1660 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1661 break;
1662 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001663 case OMPRTL__kmpc_for_static_fini: {
1664 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1665 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1666 llvm::FunctionType *FnTy =
1667 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1668 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1669 break;
1670 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001671 case OMPRTL__kmpc_push_num_threads: {
1672 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1673 // kmp_int32 num_threads)
1674 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1675 CGM.Int32Ty};
1676 llvm::FunctionType *FnTy =
1677 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1678 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1679 break;
1680 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001681 case OMPRTL__kmpc_serialized_parallel: {
1682 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1683 // global_tid);
1684 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1685 llvm::FunctionType *FnTy =
1686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1688 break;
1689 }
1690 case OMPRTL__kmpc_end_serialized_parallel: {
1691 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1692 // global_tid);
1693 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1694 llvm::FunctionType *FnTy =
1695 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1696 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1697 break;
1698 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001699 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001700 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001701 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1702 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001703 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001704 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1705 break;
1706 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001707 case OMPRTL__kmpc_master: {
1708 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1709 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1710 llvm::FunctionType *FnTy =
1711 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1712 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1713 break;
1714 }
1715 case OMPRTL__kmpc_end_master: {
1716 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1717 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1718 llvm::FunctionType *FnTy =
1719 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1720 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1721 break;
1722 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001723 case OMPRTL__kmpc_omp_taskyield: {
1724 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1725 // int end_part);
1726 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1727 llvm::FunctionType *FnTy =
1728 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1729 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1730 break;
1731 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001732 case OMPRTL__kmpc_single: {
1733 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1734 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1735 llvm::FunctionType *FnTy =
1736 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1737 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1738 break;
1739 }
1740 case OMPRTL__kmpc_end_single: {
1741 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1742 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1743 llvm::FunctionType *FnTy =
1744 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1745 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1746 break;
1747 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001748 case OMPRTL__kmpc_omp_task_alloc: {
1749 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1750 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1751 // kmp_routine_entry_t *task_entry);
1752 assert(KmpRoutineEntryPtrTy != nullptr &&
1753 "Type kmp_routine_entry_t must be created.");
1754 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1755 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1756 // Return void * and then cast to particular kmp_task_t type.
1757 llvm::FunctionType *FnTy =
1758 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1759 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1760 break;
1761 }
1762 case OMPRTL__kmpc_omp_task: {
1763 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1764 // *new_task);
1765 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1766 CGM.VoidPtrTy};
1767 llvm::FunctionType *FnTy =
1768 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1770 break;
1771 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001772 case OMPRTL__kmpc_copyprivate: {
1773 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001774 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001775 // kmp_int32 didit);
1776 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1777 auto *CpyFnTy =
1778 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001779 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001780 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1781 CGM.Int32Ty};
1782 llvm::FunctionType *FnTy =
1783 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1785 break;
1786 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001787 case OMPRTL__kmpc_reduce: {
1788 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1789 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1790 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1791 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1792 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1793 /*isVarArg=*/false);
1794 llvm::Type *TypeParams[] = {
1795 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1796 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1797 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1798 llvm::FunctionType *FnTy =
1799 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1800 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1801 break;
1802 }
1803 case OMPRTL__kmpc_reduce_nowait: {
1804 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1805 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1806 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1807 // *lck);
1808 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1809 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1810 /*isVarArg=*/false);
1811 llvm::Type *TypeParams[] = {
1812 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1813 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1814 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1815 llvm::FunctionType *FnTy =
1816 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1817 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1818 break;
1819 }
1820 case OMPRTL__kmpc_end_reduce: {
1821 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1822 // kmp_critical_name *lck);
1823 llvm::Type *TypeParams[] = {
1824 getIdentTyPointerTy(), CGM.Int32Ty,
1825 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1826 llvm::FunctionType *FnTy =
1827 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1828 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1829 break;
1830 }
1831 case OMPRTL__kmpc_end_reduce_nowait: {
1832 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1833 // kmp_critical_name *lck);
1834 llvm::Type *TypeParams[] = {
1835 getIdentTyPointerTy(), CGM.Int32Ty,
1836 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1837 llvm::FunctionType *FnTy =
1838 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1839 RTLFn =
1840 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1841 break;
1842 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001843 case OMPRTL__kmpc_omp_task_begin_if0: {
1844 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1845 // *new_task);
1846 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1847 CGM.VoidPtrTy};
1848 llvm::FunctionType *FnTy =
1849 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1850 RTLFn =
1851 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1852 break;
1853 }
1854 case OMPRTL__kmpc_omp_task_complete_if0: {
1855 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1856 // *new_task);
1857 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1858 CGM.VoidPtrTy};
1859 llvm::FunctionType *FnTy =
1860 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1861 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1862 /*Name=*/"__kmpc_omp_task_complete_if0");
1863 break;
1864 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001865 case OMPRTL__kmpc_ordered: {
1866 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1867 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1868 llvm::FunctionType *FnTy =
1869 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1870 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1871 break;
1872 }
1873 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001874 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001875 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1876 llvm::FunctionType *FnTy =
1877 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1878 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1879 break;
1880 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001881 case OMPRTL__kmpc_omp_taskwait: {
1882 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1883 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1884 llvm::FunctionType *FnTy =
1885 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1886 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1887 break;
1888 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001889 case OMPRTL__kmpc_taskgroup: {
1890 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1891 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1892 llvm::FunctionType *FnTy =
1893 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1894 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1895 break;
1896 }
1897 case OMPRTL__kmpc_end_taskgroup: {
1898 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1899 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1900 llvm::FunctionType *FnTy =
1901 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1902 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1903 break;
1904 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001905 case OMPRTL__kmpc_push_proc_bind: {
1906 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1907 // int proc_bind)
1908 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1909 llvm::FunctionType *FnTy =
1910 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1911 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1912 break;
1913 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001914 case OMPRTL__kmpc_omp_task_with_deps: {
1915 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1916 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1917 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1918 llvm::Type *TypeParams[] = {
1919 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1920 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1921 llvm::FunctionType *FnTy =
1922 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1923 RTLFn =
1924 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1925 break;
1926 }
1927 case OMPRTL__kmpc_omp_wait_deps: {
1928 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1929 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1930 // kmp_depend_info_t *noalias_dep_list);
1931 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1932 CGM.Int32Ty, CGM.VoidPtrTy,
1933 CGM.Int32Ty, CGM.VoidPtrTy};
1934 llvm::FunctionType *FnTy =
1935 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1936 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1937 break;
1938 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001939 case OMPRTL__kmpc_cancellationpoint: {
1940 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1941 // global_tid, kmp_int32 cncl_kind)
1942 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1943 llvm::FunctionType *FnTy =
1944 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1945 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1946 break;
1947 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001948 case OMPRTL__kmpc_cancel: {
1949 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1950 // kmp_int32 cncl_kind)
1951 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1952 llvm::FunctionType *FnTy =
1953 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1954 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1955 break;
1956 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001957 case OMPRTL__kmpc_push_num_teams: {
1958 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1959 // kmp_int32 num_teams, kmp_int32 num_threads)
1960 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1961 CGM.Int32Ty};
1962 llvm::FunctionType *FnTy =
1963 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1964 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1965 break;
1966 }
1967 case OMPRTL__kmpc_fork_teams: {
1968 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1969 // microtask, ...);
1970 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1971 getKmpc_MicroPointerTy()};
1972 llvm::FunctionType *FnTy =
1973 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1974 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1975 break;
1976 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001977 case OMPRTL__kmpc_taskloop: {
1978 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1979 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1980 // sched, kmp_uint64 grainsize, void *task_dup);
1981 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1982 CGM.IntTy,
1983 CGM.VoidPtrTy,
1984 CGM.IntTy,
1985 CGM.Int64Ty->getPointerTo(),
1986 CGM.Int64Ty->getPointerTo(),
1987 CGM.Int64Ty,
1988 CGM.IntTy,
1989 CGM.IntTy,
1990 CGM.Int64Ty,
1991 CGM.VoidPtrTy};
1992 llvm::FunctionType *FnTy =
1993 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1994 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1995 break;
1996 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001997 case OMPRTL__kmpc_doacross_init: {
1998 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1999 // num_dims, struct kmp_dim *dims);
2000 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2001 CGM.Int32Ty,
2002 CGM.Int32Ty,
2003 CGM.VoidPtrTy};
2004 llvm::FunctionType *FnTy =
2005 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2006 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2007 break;
2008 }
2009 case OMPRTL__kmpc_doacross_fini: {
2010 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2011 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2012 llvm::FunctionType *FnTy =
2013 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2014 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2015 break;
2016 }
2017 case OMPRTL__kmpc_doacross_post: {
2018 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2019 // *vec);
2020 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2021 CGM.Int64Ty->getPointerTo()};
2022 llvm::FunctionType *FnTy =
2023 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2024 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2025 break;
2026 }
2027 case OMPRTL__kmpc_doacross_wait: {
2028 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2029 // *vec);
2030 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2031 CGM.Int64Ty->getPointerTo()};
2032 llvm::FunctionType *FnTy =
2033 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2034 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2035 break;
2036 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002037 case OMPRTL__kmpc_task_reduction_init: {
2038 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2039 // *data);
2040 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2041 llvm::FunctionType *FnTy =
2042 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2043 RTLFn =
2044 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2045 break;
2046 }
2047 case OMPRTL__kmpc_task_reduction_get_th_data: {
2048 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2049 // *d);
2050 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2051 llvm::FunctionType *FnTy =
2052 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2053 RTLFn = CGM.CreateRuntimeFunction(
2054 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2055 break;
2056 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002057 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002058 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2059 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002060 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002061 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002062 CGM.VoidPtrTy,
2063 CGM.Int32Ty,
2064 CGM.VoidPtrPtrTy,
2065 CGM.VoidPtrPtrTy,
2066 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002067 CGM.Int64Ty->getPointerTo()};
Samuel Antaobed3c462015-10-02 16:14:20 +00002068 llvm::FunctionType *FnTy =
2069 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2070 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2071 break;
2072 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002073 case OMPRTL__tgt_target_nowait: {
2074 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2075 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2076 // int64_t *arg_types);
2077 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2078 CGM.VoidPtrTy,
2079 CGM.Int32Ty,
2080 CGM.VoidPtrPtrTy,
2081 CGM.VoidPtrPtrTy,
2082 CGM.SizeTy->getPointerTo(),
2083 CGM.Int64Ty->getPointerTo()};
2084 llvm::FunctionType *FnTy =
2085 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2086 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2087 break;
2088 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002089 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002090 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002091 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002092 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2093 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002094 CGM.VoidPtrTy,
2095 CGM.Int32Ty,
2096 CGM.VoidPtrPtrTy,
2097 CGM.VoidPtrPtrTy,
2098 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002099 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002100 CGM.Int32Ty,
2101 CGM.Int32Ty};
2102 llvm::FunctionType *FnTy =
2103 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2104 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2105 break;
2106 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002107 case OMPRTL__tgt_target_teams_nowait: {
2108 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2109 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2110 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2111 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2112 CGM.VoidPtrTy,
2113 CGM.Int32Ty,
2114 CGM.VoidPtrPtrTy,
2115 CGM.VoidPtrPtrTy,
2116 CGM.SizeTy->getPointerTo(),
2117 CGM.Int64Ty->getPointerTo(),
2118 CGM.Int32Ty,
2119 CGM.Int32Ty};
2120 llvm::FunctionType *FnTy =
2121 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2122 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2123 break;
2124 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002125 case OMPRTL__tgt_register_lib: {
2126 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2127 QualType ParamTy =
2128 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2129 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2130 llvm::FunctionType *FnTy =
2131 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2132 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2133 break;
2134 }
2135 case OMPRTL__tgt_unregister_lib: {
2136 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2137 QualType ParamTy =
2138 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2139 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2140 llvm::FunctionType *FnTy =
2141 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2142 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2143 break;
2144 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002145 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002146 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2147 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2148 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002149 CGM.Int32Ty,
2150 CGM.VoidPtrPtrTy,
2151 CGM.VoidPtrPtrTy,
2152 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002153 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002154 llvm::FunctionType *FnTy =
2155 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2156 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2157 break;
2158 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002159 case OMPRTL__tgt_target_data_begin_nowait: {
2160 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2161 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2162 // *arg_types);
2163 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2164 CGM.Int32Ty,
2165 CGM.VoidPtrPtrTy,
2166 CGM.VoidPtrPtrTy,
2167 CGM.SizeTy->getPointerTo(),
2168 CGM.Int64Ty->getPointerTo()};
2169 auto *FnTy =
2170 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2171 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2172 break;
2173 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002174 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002175 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2176 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2177 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002178 CGM.Int32Ty,
2179 CGM.VoidPtrPtrTy,
2180 CGM.VoidPtrPtrTy,
2181 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002182 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002183 llvm::FunctionType *FnTy =
2184 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2185 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2186 break;
2187 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002188 case OMPRTL__tgt_target_data_end_nowait: {
2189 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2190 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2191 // *arg_types);
2192 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2193 CGM.Int32Ty,
2194 CGM.VoidPtrPtrTy,
2195 CGM.VoidPtrPtrTy,
2196 CGM.SizeTy->getPointerTo(),
2197 CGM.Int64Ty->getPointerTo()};
2198 auto *FnTy =
2199 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2200 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2201 break;
2202 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002203 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002204 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2205 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2206 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002207 CGM.Int32Ty,
2208 CGM.VoidPtrPtrTy,
2209 CGM.VoidPtrPtrTy,
2210 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002211 CGM.Int64Ty->getPointerTo()};
Samuel Antao8d2d7302016-05-26 18:30:22 +00002212 llvm::FunctionType *FnTy =
2213 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2214 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2215 break;
2216 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002217 case OMPRTL__tgt_target_data_update_nowait: {
2218 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2219 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2220 // *arg_types);
2221 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2222 CGM.Int32Ty,
2223 CGM.VoidPtrPtrTy,
2224 CGM.VoidPtrPtrTy,
2225 CGM.SizeTy->getPointerTo(),
2226 CGM.Int64Ty->getPointerTo()};
2227 auto *FnTy =
2228 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2229 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2230 break;
2231 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002232 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002233 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002234 return RTLFn;
2235}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002236
Alexander Musman21212e42015-03-13 10:38:23 +00002237llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2238 bool IVSigned) {
2239 assert((IVSize == 32 || IVSize == 64) &&
2240 "IV size is not compatible with the omp runtime");
2241 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2242 : "__kmpc_for_static_init_4u")
2243 : (IVSigned ? "__kmpc_for_static_init_8"
2244 : "__kmpc_for_static_init_8u");
2245 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2246 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2247 llvm::Type *TypeParams[] = {
2248 getIdentTyPointerTy(), // loc
2249 CGM.Int32Ty, // tid
2250 CGM.Int32Ty, // schedtype
2251 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2252 PtrTy, // p_lower
2253 PtrTy, // p_upper
2254 PtrTy, // p_stride
2255 ITy, // incr
2256 ITy // chunk
2257 };
2258 llvm::FunctionType *FnTy =
2259 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2260 return CGM.CreateRuntimeFunction(FnTy, Name);
2261}
2262
Alexander Musman92bdaab2015-03-12 13:37:50 +00002263llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2264 bool IVSigned) {
2265 assert((IVSize == 32 || IVSize == 64) &&
2266 "IV size is not compatible with the omp runtime");
2267 auto Name =
2268 IVSize == 32
2269 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2270 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2271 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2272 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2273 CGM.Int32Ty, // tid
2274 CGM.Int32Ty, // schedtype
2275 ITy, // lower
2276 ITy, // upper
2277 ITy, // stride
2278 ITy // chunk
2279 };
2280 llvm::FunctionType *FnTy =
2281 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2282 return CGM.CreateRuntimeFunction(FnTy, Name);
2283}
2284
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002285llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2286 bool IVSigned) {
2287 assert((IVSize == 32 || IVSize == 64) &&
2288 "IV size is not compatible with the omp runtime");
2289 auto Name =
2290 IVSize == 32
2291 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2292 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2293 llvm::Type *TypeParams[] = {
2294 getIdentTyPointerTy(), // loc
2295 CGM.Int32Ty, // tid
2296 };
2297 llvm::FunctionType *FnTy =
2298 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2299 return CGM.CreateRuntimeFunction(FnTy, Name);
2300}
2301
Alexander Musman92bdaab2015-03-12 13:37:50 +00002302llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2303 bool IVSigned) {
2304 assert((IVSize == 32 || IVSize == 64) &&
2305 "IV size is not compatible with the omp runtime");
2306 auto Name =
2307 IVSize == 32
2308 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2309 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2310 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2311 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2312 llvm::Type *TypeParams[] = {
2313 getIdentTyPointerTy(), // loc
2314 CGM.Int32Ty, // tid
2315 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2316 PtrTy, // p_lower
2317 PtrTy, // p_upper
2318 PtrTy // p_stride
2319 };
2320 llvm::FunctionType *FnTy =
2321 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2322 return CGM.CreateRuntimeFunction(FnTy, Name);
2323}
2324
Alexey Bataev97720002014-11-11 04:05:39 +00002325llvm::Constant *
2326CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002327 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2328 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002329 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002330 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002331 Twine(CGM.getMangledName(VD)) + ".cache.");
2332}
2333
John McCall7f416cc2015-09-08 08:05:57 +00002334Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2335 const VarDecl *VD,
2336 Address VDAddr,
2337 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002338 if (CGM.getLangOpts().OpenMPUseTLS &&
2339 CGM.getContext().getTargetInfo().isTLSSupported())
2340 return VDAddr;
2341
John McCall7f416cc2015-09-08 08:05:57 +00002342 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002343 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002344 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2345 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002346 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2347 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002348 return Address(CGF.EmitRuntimeCall(
2349 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2350 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002351}
2352
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002353void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002354 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002355 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2356 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2357 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002358 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2359 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002360 OMPLoc);
2361 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2362 // to register constructor/destructor for variable.
2363 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002364 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2365 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002366 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002367 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002368 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002369}
2370
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002371llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002372 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002373 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002374 if (CGM.getLangOpts().OpenMPUseTLS &&
2375 CGM.getContext().getTargetInfo().isTLSSupported())
2376 return nullptr;
2377
Alexey Bataev97720002014-11-11 04:05:39 +00002378 VD = VD->getDefinition(CGM.getContext());
2379 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2380 ThreadPrivateWithDefinition.insert(VD);
2381 QualType ASTTy = VD->getType();
2382
2383 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2384 auto Init = VD->getAnyInitializer();
2385 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2386 // Generate function that re-emits the declaration's initializer into the
2387 // threadprivate copy of the variable VD
2388 CodeGenFunction CtorCGF(CGM);
2389 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002390 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2391 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002392 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002393 Args.push_back(&Dst);
2394
John McCallc56a8b32016-03-11 04:30:31 +00002395 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2396 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002397 auto FTy = CGM.getTypes().GetFunctionType(FI);
2398 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002399 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002400 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002401 Args, Loc, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002402 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002403 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002404 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002405 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002406 Arg = CtorCGF.Builder.CreateElementBitCast(
2407 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002408 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2409 /*IsInitializer=*/true);
2410 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002411 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002412 CGM.getContext().VoidPtrTy, Dst.getLocation());
2413 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2414 CtorCGF.FinishFunction();
2415 Ctor = Fn;
2416 }
2417 if (VD->getType().isDestructedType() != QualType::DK_none) {
2418 // Generate function that emits destructor call for the threadprivate copy
2419 // of the variable VD
2420 CodeGenFunction DtorCGF(CGM);
2421 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002422 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2423 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002424 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002425 Args.push_back(&Dst);
2426
John McCallc56a8b32016-03-11 04:30:31 +00002427 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2428 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002429 auto FTy = CGM.getTypes().GetFunctionType(FI);
2430 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002431 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002432 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002433 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002434 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002435 // Create a scope with an artificial location for the body of this function.
2436 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002437 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2438 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002439 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2440 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002441 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2442 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2443 DtorCGF.FinishFunction();
2444 Dtor = Fn;
2445 }
2446 // Do not emit init function if it is not required.
2447 if (!Ctor && !Dtor)
2448 return nullptr;
2449
2450 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2451 auto CopyCtorTy =
2452 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2453 /*isVarArg=*/false)->getPointerTo();
2454 // Copying constructor for the threadprivate variable.
2455 // Must be NULL - reserved by runtime, but currently it requires that this
2456 // parameter is always NULL. Otherwise it fires assertion.
2457 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2458 if (Ctor == nullptr) {
2459 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2460 /*isVarArg=*/false)->getPointerTo();
2461 Ctor = llvm::Constant::getNullValue(CtorTy);
2462 }
2463 if (Dtor == nullptr) {
2464 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2465 /*isVarArg=*/false)->getPointerTo();
2466 Dtor = llvm::Constant::getNullValue(DtorTy);
2467 }
2468 if (!CGF) {
2469 auto InitFunctionTy =
2470 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2471 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002472 InitFunctionTy, ".__omp_threadprivate_init_.",
2473 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002474 CodeGenFunction InitCGF(CGM);
2475 FunctionArgList ArgList;
2476 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2477 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002478 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002479 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002480 InitCGF.FinishFunction();
2481 return InitFunction;
2482 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002483 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002484 }
2485 return nullptr;
2486}
2487
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002488Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2489 QualType VarType,
2490 StringRef Name) {
2491 llvm::Twine VarName(Name, ".artificial.");
2492 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2493 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2494 llvm::Value *Args[] = {
2495 emitUpdateLocation(CGF, SourceLocation()),
2496 getThreadID(CGF, SourceLocation()),
2497 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2498 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2499 /*IsSigned=*/false),
2500 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2501 return Address(
2502 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2503 CGF.EmitRuntimeCall(
2504 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2505 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2506 CGM.getPointerAlign());
2507}
2508
Alexey Bataev1d677132015-04-22 13:57:31 +00002509/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2510/// function. Here is the logic:
2511/// if (Cond) {
2512/// ThenGen();
2513/// } else {
2514/// ElseGen();
2515/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002516void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2517 const RegionCodeGenTy &ThenGen,
2518 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002519 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2520
2521 // If the condition constant folds and can be elided, try to avoid emitting
2522 // the condition and the dead arm of the if/else.
2523 bool CondConstant;
2524 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002525 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002526 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002527 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002528 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002529 return;
2530 }
2531
2532 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2533 // emit the conditional branch.
2534 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2535 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2536 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2537 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2538
2539 // Emit the 'then' code.
2540 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002541 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002542 CGF.EmitBranch(ContBlock);
2543 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002544 // There is no need to emit line number for unconditional branch.
2545 (void)ApplyDebugLocation::CreateEmpty(CGF);
2546 CGF.EmitBlock(ElseBlock);
2547 ElseGen(CGF);
2548 // There is no need to emit line number for unconditional branch.
2549 (void)ApplyDebugLocation::CreateEmpty(CGF);
2550 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002551 // Emit the continuation block for code after the if.
2552 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002553}
2554
Alexey Bataev1d677132015-04-22 13:57:31 +00002555void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2556 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002557 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002558 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002559 if (!CGF.HaveInsertPoint())
2560 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002561 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002562 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2563 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002564 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002565 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002566 llvm::Value *Args[] = {
2567 RTLoc,
2568 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002569 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002570 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2571 RealArgs.append(std::begin(Args), std::end(Args));
2572 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2573
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002574 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002575 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2576 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002577 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2578 PrePostActionTy &) {
2579 auto &RT = CGF.CGM.getOpenMPRuntime();
2580 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002581 // Build calls:
2582 // __kmpc_serialized_parallel(&Loc, GTid);
2583 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002584 CGF.EmitRuntimeCall(
2585 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002586
Alexey Bataev1d677132015-04-22 13:57:31 +00002587 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002588 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002589 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002590 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2591 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002592 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002593 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2594 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2595 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2596 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002597 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002598
Alexey Bataev1d677132015-04-22 13:57:31 +00002599 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002600 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002601 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002602 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2603 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002604 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002605 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002606 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002607 else {
2608 RegionCodeGenTy ThenRCG(ThenGen);
2609 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002610 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002611}
2612
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002613// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002614// thread-ID variable (it is passed in a first argument of the outlined function
2615// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2616// regular serial code region, get thread ID by calling kmp_int32
2617// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2618// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002619Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2620 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002621 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002622 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002623 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002624 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002625
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002626 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002627 auto Int32Ty =
2628 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2629 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2630 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002631 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002632
2633 return ThreadIDTemp;
2634}
2635
Alexey Bataev97720002014-11-11 04:05:39 +00002636llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002637CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002638 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002639 SmallString<256> Buffer;
2640 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002641 Out << Name;
2642 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002643 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2644 if (Elem.second) {
2645 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002646 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002647 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002648 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002649
David Blaikie13156b62014-11-19 03:06:06 +00002650 return Elem.second = new llvm::GlobalVariable(
2651 CGM.getModule(), Ty, /*IsConstant*/ false,
2652 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2653 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002654}
2655
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002656llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002657 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002658 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002659}
2660
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002661namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002662/// Common pre(post)-action for different OpenMP constructs.
2663class CommonActionTy final : public PrePostActionTy {
2664 llvm::Value *EnterCallee;
2665 ArrayRef<llvm::Value *> EnterArgs;
2666 llvm::Value *ExitCallee;
2667 ArrayRef<llvm::Value *> ExitArgs;
2668 bool Conditional;
2669 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002670
2671public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002672 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2673 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2674 bool Conditional = false)
2675 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2676 ExitArgs(ExitArgs), Conditional(Conditional) {}
2677 void Enter(CodeGenFunction &CGF) override {
2678 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2679 if (Conditional) {
2680 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2681 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2682 ContBlock = CGF.createBasicBlock("omp_if.end");
2683 // Generate the branch (If-stmt)
2684 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2685 CGF.EmitBlock(ThenBlock);
2686 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002687 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002688 void Done(CodeGenFunction &CGF) {
2689 // Emit the rest of blocks/branches
2690 CGF.EmitBranch(ContBlock);
2691 CGF.EmitBlock(ContBlock, true);
2692 }
2693 void Exit(CodeGenFunction &CGF) override {
2694 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002695 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002696};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002697} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002698
2699void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2700 StringRef CriticalName,
2701 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002702 SourceLocation Loc, const Expr *Hint) {
2703 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002704 // CriticalOpGen();
2705 // __kmpc_end_critical(ident_t *, gtid, Lock);
2706 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002707 if (!CGF.HaveInsertPoint())
2708 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002709 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2710 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002711 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2712 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002713 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002714 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2715 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2716 }
2717 CommonActionTy Action(
2718 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2719 : OMPRTL__kmpc_critical),
2720 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2721 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002722 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002723}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002724
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002725void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002726 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002727 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002728 if (!CGF.HaveInsertPoint())
2729 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002730 // if(__kmpc_master(ident_t *, gtid)) {
2731 // MasterOpGen();
2732 // __kmpc_end_master(ident_t *, gtid);
2733 // }
2734 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002735 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002736 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2737 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2738 /*Conditional=*/true);
2739 MasterOpGen.setAction(Action);
2740 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2741 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002742}
2743
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002744void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2745 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002746 if (!CGF.HaveInsertPoint())
2747 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002748 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2749 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002750 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002751 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002752 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002753 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2754 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002755}
2756
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002757void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2758 const RegionCodeGenTy &TaskgroupOpGen,
2759 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002760 if (!CGF.HaveInsertPoint())
2761 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002762 // __kmpc_taskgroup(ident_t *, gtid);
2763 // TaskgroupOpGen();
2764 // __kmpc_end_taskgroup(ident_t *, gtid);
2765 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002766 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2767 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2768 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2769 Args);
2770 TaskgroupOpGen.setAction(Action);
2771 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002772}
2773
John McCall7f416cc2015-09-08 08:05:57 +00002774/// Given an array of pointers to variables, project the address of a
2775/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002776static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2777 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002778 // Pull out the pointer to the variable.
2779 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002780 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002781 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2782
2783 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002784 Addr = CGF.Builder.CreateElementBitCast(
2785 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002786 return Addr;
2787}
2788
Alexey Bataeva63048e2015-03-23 06:18:07 +00002789static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002790 CodeGenModule &CGM, llvm::Type *ArgsType,
2791 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002792 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2793 SourceLocation Loc) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002794 auto &C = CGM.getContext();
2795 // void copy_func(void *LHSArg, void *RHSArg);
2796 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002797 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2798 ImplicitParamDecl::Other);
2799 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2800 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002801 Args.push_back(&LHSArg);
2802 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002803 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002804 auto *Fn = llvm::Function::Create(
2805 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2806 ".omp.copyprivate.copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002807 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002808 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002809 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002810 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002811 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002812 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2813 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2814 ArgsType), CGF.getPointerAlign());
2815 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2816 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2817 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002818 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2819 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2820 // ...
2821 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002822 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002823 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2824 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2825
2826 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2827 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2828
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002829 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2830 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002831 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002832 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002833 CGF.FinishFunction();
2834 return Fn;
2835}
2836
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002837void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002838 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002839 SourceLocation Loc,
2840 ArrayRef<const Expr *> CopyprivateVars,
2841 ArrayRef<const Expr *> SrcExprs,
2842 ArrayRef<const Expr *> DstExprs,
2843 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002844 if (!CGF.HaveInsertPoint())
2845 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002846 assert(CopyprivateVars.size() == SrcExprs.size() &&
2847 CopyprivateVars.size() == DstExprs.size() &&
2848 CopyprivateVars.size() == AssignmentOps.size());
2849 auto &C = CGM.getContext();
2850 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002851 // if(__kmpc_single(ident_t *, gtid)) {
2852 // SingleOpGen();
2853 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002854 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002855 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002856 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2857 // <copy_func>, did_it);
2858
John McCall7f416cc2015-09-08 08:05:57 +00002859 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002860 if (!CopyprivateVars.empty()) {
2861 // int32 did_it = 0;
2862 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2863 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002864 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002865 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002866 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002867 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002868 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2869 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2870 /*Conditional=*/true);
2871 SingleOpGen.setAction(Action);
2872 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2873 if (DidIt.isValid()) {
2874 // did_it = 1;
2875 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2876 }
2877 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002878 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2879 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002880 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002881 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2882 auto CopyprivateArrayTy =
2883 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2884 /*IndexTypeQuals=*/0);
2885 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002886 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002887 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2888 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002889 Address Elem = CGF.Builder.CreateConstArrayGEP(
2890 CopyprivateList, I, CGF.getPointerSize());
2891 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002892 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002893 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2894 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002895 }
2896 // Build function that copies private values from single region to all other
2897 // threads in the corresponding parallel region.
2898 auto *CpyFn = emitCopyprivateCopyFunction(
2899 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002900 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002901 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002902 Address CL =
2903 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2904 CGF.VoidPtrTy);
2905 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002906 llvm::Value *Args[] = {
2907 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2908 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002909 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002910 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002911 CpyFn, // void (*) (void *, void *) <copy_func>
2912 DidItVal // i32 did_it
2913 };
2914 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2915 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002916}
2917
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002918void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2919 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002920 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002921 if (!CGF.HaveInsertPoint())
2922 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002923 // __kmpc_ordered(ident_t *, gtid);
2924 // OrderedOpGen();
2925 // __kmpc_end_ordered(ident_t *, gtid);
2926 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002927 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002928 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002929 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2930 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2931 Args);
2932 OrderedOpGen.setAction(Action);
2933 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2934 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002935 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002936 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002937}
2938
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002939void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002940 OpenMPDirectiveKind Kind, bool EmitChecks,
2941 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002942 if (!CGF.HaveInsertPoint())
2943 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002944 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002945 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002946 unsigned Flags;
2947 if (Kind == OMPD_for)
2948 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2949 else if (Kind == OMPD_sections)
2950 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2951 else if (Kind == OMPD_single)
2952 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2953 else if (Kind == OMPD_barrier)
2954 Flags = OMP_IDENT_BARRIER_EXPL;
2955 else
2956 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002957 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2958 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002959 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2960 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002961 if (auto *OMPRegionInfo =
2962 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002963 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002964 auto *Result = CGF.EmitRuntimeCall(
2965 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002966 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002967 // if (__kmpc_cancel_barrier()) {
2968 // exit from construct;
2969 // }
2970 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2971 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2972 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2973 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2974 CGF.EmitBlock(ExitBB);
2975 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002976 auto CancelDestination =
2977 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002978 CGF.EmitBranchThroughCleanup(CancelDestination);
2979 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2980 }
2981 return;
2982 }
2983 }
2984 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002985}
2986
Alexander Musmanc6388682014-12-15 07:07:06 +00002987/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2988static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002989 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002990 switch (ScheduleKind) {
2991 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002992 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2993 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002994 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002995 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002996 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002997 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002998 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002999 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3000 case OMPC_SCHEDULE_auto:
3001 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003002 case OMPC_SCHEDULE_unknown:
3003 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003004 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003005 }
3006 llvm_unreachable("Unexpected runtime schedule");
3007}
3008
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003009/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3010static OpenMPSchedType
3011getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3012 // only static is allowed for dist_schedule
3013 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3014}
3015
Alexander Musmanc6388682014-12-15 07:07:06 +00003016bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3017 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003018 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003019 return Schedule == OMP_sch_static;
3020}
3021
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003022bool CGOpenMPRuntime::isStaticNonchunked(
3023 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3024 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3025 return Schedule == OMP_dist_sch_static;
3026}
3027
3028
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003029bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003030 auto Schedule =
3031 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003032 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3033 return Schedule != OMP_sch_static;
3034}
3035
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003036static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3037 OpenMPScheduleClauseModifier M1,
3038 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003039 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003040 switch (M1) {
3041 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003042 Modifier = OMP_sch_modifier_monotonic;
3043 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003044 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003045 Modifier = OMP_sch_modifier_nonmonotonic;
3046 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003047 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003048 if (Schedule == OMP_sch_static_chunked)
3049 Schedule = OMP_sch_static_balanced_chunked;
3050 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003051 case OMPC_SCHEDULE_MODIFIER_last:
3052 case OMPC_SCHEDULE_MODIFIER_unknown:
3053 break;
3054 }
3055 switch (M2) {
3056 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003057 Modifier = OMP_sch_modifier_monotonic;
3058 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003059 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003060 Modifier = OMP_sch_modifier_nonmonotonic;
3061 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003062 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003063 if (Schedule == OMP_sch_static_chunked)
3064 Schedule = OMP_sch_static_balanced_chunked;
3065 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003066 case OMPC_SCHEDULE_MODIFIER_last:
3067 case OMPC_SCHEDULE_MODIFIER_unknown:
3068 break;
3069 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003070 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003071}
3072
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003073void CGOpenMPRuntime::emitForDispatchInit(
3074 CodeGenFunction &CGF, SourceLocation Loc,
3075 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3076 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003077 if (!CGF.HaveInsertPoint())
3078 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003079 OpenMPSchedType Schedule = getRuntimeSchedule(
3080 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003081 assert(Ordered ||
3082 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003083 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3084 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003085 // Call __kmpc_dispatch_init(
3086 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3087 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3088 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003089
John McCall7f416cc2015-09-08 08:05:57 +00003090 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003091 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3092 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003093 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003094 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3095 CGF.Builder.getInt32(addMonoNonMonoModifier(
3096 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003097 DispatchValues.LB, // Lower
3098 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003099 CGF.Builder.getIntN(IVSize, 1), // Stride
3100 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003101 };
3102 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3103}
3104
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003105static void emitForStaticInitCall(
3106 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3107 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3108 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003109 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003110 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003111 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003112
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003113 assert(!Values.Ordered);
3114 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3115 Schedule == OMP_sch_static_balanced_chunked ||
3116 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3117 Schedule == OMP_dist_sch_static ||
3118 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003119
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003120 // Call __kmpc_for_static_init(
3121 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3122 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3123 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3124 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3125 llvm::Value *Chunk = Values.Chunk;
3126 if (Chunk == nullptr) {
3127 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3128 Schedule == OMP_dist_sch_static) &&
3129 "expected static non-chunked schedule");
3130 // If the Chunk was not specified in the clause - use default value 1.
3131 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3132 } else {
3133 assert((Schedule == OMP_sch_static_chunked ||
3134 Schedule == OMP_sch_static_balanced_chunked ||
3135 Schedule == OMP_ord_static_chunked ||
3136 Schedule == OMP_dist_sch_static_chunked) &&
3137 "expected static chunked schedule");
3138 }
3139 llvm::Value *Args[] = {
3140 UpdateLocation,
3141 ThreadId,
3142 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3143 M2)), // Schedule type
3144 Values.IL.getPointer(), // &isLastIter
3145 Values.LB.getPointer(), // &LB
3146 Values.UB.getPointer(), // &UB
3147 Values.ST.getPointer(), // &Stride
3148 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3149 Chunk // Chunk
3150 };
3151 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003152}
3153
John McCall7f416cc2015-09-08 08:05:57 +00003154void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3155 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003156 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003157 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003158 const StaticRTInput &Values) {
3159 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3160 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3161 assert(isOpenMPWorksharingDirective(DKind) &&
3162 "Expected loop-based or sections-based directive.");
3163 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3164 isOpenMPLoopDirective(DKind)
3165 ? OMP_IDENT_WORK_LOOP
3166 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003167 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003168 auto *StaticInitFunction =
3169 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003170 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003171 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003172}
John McCall7f416cc2015-09-08 08:05:57 +00003173
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003174void CGOpenMPRuntime::emitDistributeStaticInit(
3175 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003176 OpenMPDistScheduleClauseKind SchedKind,
3177 const CGOpenMPRuntime::StaticRTInput &Values) {
3178 OpenMPSchedType ScheduleNum =
3179 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3180 auto *UpdatedLocation =
3181 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003182 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003183 auto *StaticInitFunction =
3184 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003185 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3186 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003187 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003188}
3189
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003190void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003191 SourceLocation Loc,
3192 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003193 if (!CGF.HaveInsertPoint())
3194 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003195 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003196 llvm::Value *Args[] = {
3197 emitUpdateLocation(CGF, Loc,
3198 isOpenMPDistributeDirective(DKind)
3199 ? OMP_IDENT_WORK_DISTRIBUTE
3200 : isOpenMPLoopDirective(DKind)
3201 ? OMP_IDENT_WORK_LOOP
3202 : OMP_IDENT_WORK_SECTIONS),
3203 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003204 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3205 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003206}
3207
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003208void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3209 SourceLocation Loc,
3210 unsigned IVSize,
3211 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003212 if (!CGF.HaveInsertPoint())
3213 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003214 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003215 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003216 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3217}
3218
Alexander Musman92bdaab2015-03-12 13:37:50 +00003219llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3220 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003221 bool IVSigned, Address IL,
3222 Address LB, Address UB,
3223 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003224 // Call __kmpc_dispatch_next(
3225 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3226 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3227 // kmp_int[32|64] *p_stride);
3228 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003229 emitUpdateLocation(CGF, Loc),
3230 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003231 IL.getPointer(), // &isLastIter
3232 LB.getPointer(), // &Lower
3233 UB.getPointer(), // &Upper
3234 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003235 };
3236 llvm::Value *Call =
3237 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3238 return CGF.EmitScalarConversion(
3239 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003240 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003241}
3242
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003243void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3244 llvm::Value *NumThreads,
3245 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003246 if (!CGF.HaveInsertPoint())
3247 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003248 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3249 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003250 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003251 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003252 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3253 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003254}
3255
Alexey Bataev7f210c62015-06-18 13:40:03 +00003256void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3257 OpenMPProcBindClauseKind ProcBind,
3258 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003259 if (!CGF.HaveInsertPoint())
3260 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003261 // Constants for proc bind value accepted by the runtime.
3262 enum ProcBindTy {
3263 ProcBindFalse = 0,
3264 ProcBindTrue,
3265 ProcBindMaster,
3266 ProcBindClose,
3267 ProcBindSpread,
3268 ProcBindIntel,
3269 ProcBindDefault
3270 } RuntimeProcBind;
3271 switch (ProcBind) {
3272 case OMPC_PROC_BIND_master:
3273 RuntimeProcBind = ProcBindMaster;
3274 break;
3275 case OMPC_PROC_BIND_close:
3276 RuntimeProcBind = ProcBindClose;
3277 break;
3278 case OMPC_PROC_BIND_spread:
3279 RuntimeProcBind = ProcBindSpread;
3280 break;
3281 case OMPC_PROC_BIND_unknown:
3282 llvm_unreachable("Unsupported proc_bind value.");
3283 }
3284 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3285 llvm::Value *Args[] = {
3286 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3287 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3288 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3289}
3290
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003291void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3292 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003293 if (!CGF.HaveInsertPoint())
3294 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003295 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003296 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3297 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003298}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003299
Alexey Bataev62b63b12015-03-10 07:28:44 +00003300namespace {
3301/// \brief Indexes of fields for type kmp_task_t.
3302enum KmpTaskTFields {
3303 /// \brief List of shared variables.
3304 KmpTaskTShareds,
3305 /// \brief Task routine.
3306 KmpTaskTRoutine,
3307 /// \brief Partition id for the untied tasks.
3308 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003309 /// Function with call of destructors for private variables.
3310 Data1,
3311 /// Task priority.
3312 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003313 /// (Taskloops only) Lower bound.
3314 KmpTaskTLowerBound,
3315 /// (Taskloops only) Upper bound.
3316 KmpTaskTUpperBound,
3317 /// (Taskloops only) Stride.
3318 KmpTaskTStride,
3319 /// (Taskloops only) Is last iteration flag.
3320 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003321 /// (Taskloops only) Reduction data.
3322 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003323};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003324} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003325
Samuel Antaoee8fb302016-01-06 13:42:12 +00003326bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3327 // FIXME: Add other entries type when they become supported.
3328 return OffloadEntriesTargetRegion.empty();
3329}
3330
3331/// \brief Initialize target region entry.
3332void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3333 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3334 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003335 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003336 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3337 "only required for the device "
3338 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003339 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003340 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3341 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003342 ++OffloadingEntriesNum;
3343}
3344
3345void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3346 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3347 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003348 llvm::Constant *Addr, llvm::Constant *ID,
3349 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003350 // If we are emitting code for a target, the entry is already initialized,
3351 // only has to be registered.
3352 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003353 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003354 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003355 auto &Entry =
3356 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003357 assert(Entry.isValid() && "Entry not initialized!");
3358 Entry.setAddress(Addr);
3359 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003360 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003361 return;
3362 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003363 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003364 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003365 }
3366}
3367
3368bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003369 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3370 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003371 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3372 if (PerDevice == OffloadEntriesTargetRegion.end())
3373 return false;
3374 auto PerFile = PerDevice->second.find(FileID);
3375 if (PerFile == PerDevice->second.end())
3376 return false;
3377 auto PerParentName = PerFile->second.find(ParentName);
3378 if (PerParentName == PerFile->second.end())
3379 return false;
3380 auto PerLine = PerParentName->second.find(LineNum);
3381 if (PerLine == PerParentName->second.end())
3382 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003383 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003384 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003385 return false;
3386 return true;
3387}
3388
3389void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3390 const OffloadTargetRegionEntryInfoActTy &Action) {
3391 // Scan all target region entries and perform the provided action.
3392 for (auto &D : OffloadEntriesTargetRegion)
3393 for (auto &F : D.second)
3394 for (auto &P : F.second)
3395 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003396 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003397}
3398
3399/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3400/// \a Codegen. This is used to emit the two functions that register and
3401/// unregister the descriptor of the current compilation unit.
3402static llvm::Function *
3403createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3404 const RegionCodeGenTy &Codegen) {
3405 auto &C = CGM.getContext();
3406 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003407 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003408 Args.push_back(&DummyPtr);
3409
3410 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003411 // Disable debug info for global (de-)initializer because they are not part of
3412 // some particular construct.
3413 CGF.disableDebugInfo();
John McCallc56a8b32016-03-11 04:30:31 +00003414 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003415 auto FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003416 auto *Fn = CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI);
3417 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003418 Codegen(CGF);
3419 CGF.FinishFunction();
3420 return Fn;
3421}
3422
3423llvm::Function *
3424CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003425 // If we don't have entries or if we are emitting code for the device, we
3426 // don't need to do anything.
3427 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3428 return nullptr;
3429
3430 auto &M = CGM.getModule();
3431 auto &C = CGM.getContext();
3432
3433 // Get list of devices we care about
3434 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3435
3436 // We should be creating an offloading descriptor only if there are devices
3437 // specified.
3438 assert(!Devices.empty() && "No OpenMP offloading devices??");
3439
3440 // Create the external variables that will point to the begin and end of the
3441 // host entries section. These will be defined by the linker.
3442 auto *OffloadEntryTy =
3443 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3444 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3445 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003446 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003447 ".omp_offloading.entries_begin");
3448 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3449 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003450 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451 ".omp_offloading.entries_end");
3452
3453 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003454 auto *DeviceImageTy = cast<llvm::StructType>(
3455 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003456 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003457 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003458
3459 for (unsigned i = 0; i < Devices.size(); ++i) {
3460 StringRef T = Devices[i].getTriple();
3461 auto *ImgBegin = new llvm::GlobalVariable(
3462 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003463 /*Initializer=*/nullptr,
3464 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003465 auto *ImgEnd = new llvm::GlobalVariable(
3466 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003467 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003468
John McCall6c9f1fdb2016-11-19 08:17:24 +00003469 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3470 Dev.add(ImgBegin);
3471 Dev.add(ImgEnd);
3472 Dev.add(HostEntriesBegin);
3473 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003474 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003475 }
3476
3477 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003478 llvm::GlobalVariable *DeviceImages =
3479 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3480 CGM.getPointerAlign(),
3481 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003482 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003483
3484 // This is a Zero array to be used in the creation of the constant expressions
3485 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3486 llvm::Constant::getNullValue(CGM.Int32Ty)};
3487
3488 // Create the target region descriptor.
3489 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3490 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003491 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003492 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3493 DescInit.addInt(CGM.Int32Ty, Devices.size());
3494 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3495 DeviceImages,
3496 Index));
3497 DescInit.add(HostEntriesBegin);
3498 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003499
John McCall6c9f1fdb2016-11-19 08:17:24 +00003500 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3501 CGM.getPointerAlign(),
3502 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003503
3504 // Emit code to register or unregister the descriptor at execution
3505 // startup or closing, respectively.
3506
3507 // Create a variable to drive the registration and unregistration of the
3508 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3509 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3510 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003511 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003512
3513 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003514 CGM, ".omp_offloading.descriptor_unreg",
3515 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003516 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3517 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003518 });
3519 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003520 CGM, ".omp_offloading.descriptor_reg",
3521 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003522 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3523 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003524 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3525 });
George Rokos29d0f002017-05-27 03:03:13 +00003526 if (CGM.supportsCOMDAT()) {
3527 // It is sufficient to call registration function only once, so create a
3528 // COMDAT group for registration/unregistration functions and associated
3529 // data. That would reduce startup time and code size. Registration
3530 // function serves as a COMDAT group key.
3531 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3532 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3533 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3534 RegFn->setComdat(ComdatKey);
3535 UnRegFn->setComdat(ComdatKey);
3536 DeviceImages->setComdat(ComdatKey);
3537 Desc->setComdat(ComdatKey);
3538 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003539 return RegFn;
3540}
3541
Samuel Antao2de62b02016-02-13 23:35:10 +00003542void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003543 llvm::Constant *Addr, uint64_t Size,
3544 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003545 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003546 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3547 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3548 llvm::LLVMContext &C = CGM.getModule().getContext();
3549 llvm::Module &M = CGM.getModule();
3550
3551 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003552 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003553
3554 // Create constant string with the name.
3555 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3556
3557 llvm::GlobalVariable *Str =
3558 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3559 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3560 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003561 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003562 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3563
John McCall6c9f1fdb2016-11-19 08:17:24 +00003564 // We can't have any padding between symbols, so we need to have 1-byte
3565 // alignment.
3566 auto Align = CharUnits::fromQuantity(1);
3567
Samuel Antaoee8fb302016-01-06 13:42:12 +00003568 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003569 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003570 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3571 EntryInit.add(AddrPtr);
3572 EntryInit.add(StrPtr);
3573 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003574 EntryInit.addInt(CGM.Int32Ty, Flags);
3575 EntryInit.addInt(CGM.Int32Ty, 0);
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00003576 llvm::GlobalVariable *Entry = EntryInit.finishAndCreateGlobal(
3577 Twine(".omp_offloading.entry.") + Name, Align,
3578 /*constant*/ true, llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003579
3580 // The entry has to be created in the section the linker expects it to be.
3581 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003582}
3583
3584void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3585 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003586 // can easily figure out what to emit. The produced metadata looks like
3587 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003588 //
3589 // !omp_offload.info = !{!1, ...}
3590 //
3591 // Right now we only generate metadata for function that contain target
3592 // regions.
3593
3594 // If we do not have entries, we dont need to do anything.
3595 if (OffloadEntriesInfoManager.empty())
3596 return;
3597
3598 llvm::Module &M = CGM.getModule();
3599 llvm::LLVMContext &C = M.getContext();
3600 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3601 OrderedEntries(OffloadEntriesInfoManager.size());
3602
3603 // Create the offloading info metadata node.
3604 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3605
Simon Pilgrim2c518802017-03-30 14:13:19 +00003606 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003607 auto getMDInt = [&](unsigned v) {
3608 return llvm::ConstantAsMetadata::get(
3609 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3610 };
3611
3612 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3613
3614 // Create function that emits metadata for each target region entry;
3615 auto &&TargetRegionMetadataEmitter = [&](
3616 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003617 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3618 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3619 // Generate metadata for target regions. Each entry of this metadata
3620 // contains:
3621 // - Entry 0 -> Kind of this type of metadata (0).
3622 // - Entry 1 -> Device ID of the file where the entry was identified.
3623 // - Entry 2 -> File ID of the file where the entry was identified.
3624 // - Entry 3 -> Mangled name of the function where the entry was identified.
3625 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003626 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003627 // The first element of the metadata node is the kind.
3628 Ops.push_back(getMDInt(E.getKind()));
3629 Ops.push_back(getMDInt(DeviceID));
3630 Ops.push_back(getMDInt(FileID));
3631 Ops.push_back(getMDString(ParentName));
3632 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003633 Ops.push_back(getMDInt(E.getOrder()));
3634
3635 // Save this entry in the right position of the ordered entries array.
3636 OrderedEntries[E.getOrder()] = &E;
3637
3638 // Add metadata to the named metadata node.
3639 MD->addOperand(llvm::MDNode::get(C, Ops));
3640 };
3641
3642 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3643 TargetRegionMetadataEmitter);
3644
3645 for (auto *E : OrderedEntries) {
3646 assert(E && "All ordered entries must exist!");
3647 if (auto *CE =
3648 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3649 E)) {
3650 assert(CE->getID() && CE->getAddress() &&
3651 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003652 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003653 } else
3654 llvm_unreachable("Unsupported entry kind.");
3655 }
3656}
3657
3658/// \brief Loads all the offload entries information from the host IR
3659/// metadata.
3660void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3661 // If we are in target mode, load the metadata from the host IR. This code has
3662 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3663
3664 if (!CGM.getLangOpts().OpenMPIsDevice)
3665 return;
3666
3667 if (CGM.getLangOpts().OMPHostIRFile.empty())
3668 return;
3669
3670 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3671 if (Buf.getError())
3672 return;
3673
3674 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003675 auto ME = expectedToErrorOrAndEmitErrors(
3676 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003677
3678 if (ME.getError())
3679 return;
3680
3681 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3682 if (!MD)
3683 return;
3684
George Burgess IV00f70bd2018-03-01 05:43:23 +00003685 for (llvm::MDNode *MN : MD->operands()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003686 auto getMDInt = [&](unsigned Idx) {
3687 llvm::ConstantAsMetadata *V =
3688 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3689 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3690 };
3691
3692 auto getMDString = [&](unsigned Idx) {
3693 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3694 return V->getString();
3695 };
3696
3697 switch (getMDInt(0)) {
3698 default:
3699 llvm_unreachable("Unexpected metadata!");
3700 break;
3701 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3702 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3703 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3704 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3705 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003706 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003707 break;
3708 }
3709 }
3710}
3711
Alexey Bataev62b63b12015-03-10 07:28:44 +00003712void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3713 if (!KmpRoutineEntryPtrTy) {
3714 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3715 auto &C = CGM.getContext();
3716 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3717 FunctionProtoType::ExtProtoInfo EPI;
3718 KmpRoutineEntryPtrQTy = C.getPointerType(
3719 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3720 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3721 }
3722}
3723
Alexey Bataevc71a4092015-09-11 10:29:41 +00003724static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3725 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003726 auto *Field = FieldDecl::Create(
3727 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3728 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3729 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3730 Field->setAccess(AS_public);
3731 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003732 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003733}
3734
Samuel Antaoee8fb302016-01-06 13:42:12 +00003735QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3736
3737 // Make sure the type of the entry is already created. This is the type we
3738 // have to create:
3739 // struct __tgt_offload_entry{
3740 // void *addr; // Pointer to the offload entry info.
3741 // // (function or global)
3742 // char *name; // Name of the function or global.
3743 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003744 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3745 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003746 // };
3747 if (TgtOffloadEntryQTy.isNull()) {
3748 ASTContext &C = CGM.getContext();
3749 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3750 RD->startDefinition();
3751 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3752 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3753 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003754 addFieldToRecordDecl(
3755 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3756 addFieldToRecordDecl(
3757 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003758 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00003759 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003760 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());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003953 CGM.SetInternalFunctionAttributes(GlobalDecl(), 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 Bataev1e491372018-01-23 18:44:14 +00003980 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
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);
Alexey Bataev1e491372018-01-23 18:44:14 +00004003 auto *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004004 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4005 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004006 auto *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004007 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4008 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004009 auto *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004010 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4011 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004012 auto *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004013 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4014 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004015 auto *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
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());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004053 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004054 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());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004143 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004144 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);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004187 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4188 ? OMPD_taskloop
4189 : OMPD_task;
4190 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4191 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004192 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004193 bool IsTargetTask =
4194 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4195 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4196 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4197 // PointersArray and SizesArray. The original variables for these arrays are
4198 // not captured and we get their addresses explicitly.
4199 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004200 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004201 SrcBase = CGF.MakeAddrLValue(
4202 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4203 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4204 SharedsTy);
4205 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004206 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4207 for (auto &&Pair : Privates) {
4208 auto *VD = Pair.second.PrivateCopy;
4209 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004210 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4211 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004212 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004213 if (auto *Elem = Pair.second.PrivateElemInit) {
4214 auto *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004215 // Check if the variable is the target-based BasePointersArray,
4216 // PointersArray or SizesArray.
4217 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004218 QualType Type = OriginalVD->getType();
Alexey Bataev8451efa2018-01-15 19:06:12 +00004219 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4220 if (IsTargetTask && !SharedField) {
4221 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4222 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4223 cast<CapturedDecl>(OriginalVD->getDeclContext())
4224 ->getNumParams() == 0 &&
4225 isa<TranslationUnitDecl>(
4226 cast<CapturedDecl>(OriginalVD->getDeclContext())
4227 ->getDeclContext()) &&
4228 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004229 SharedRefLValue =
4230 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4231 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004232 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4233 SharedRefLValue = CGF.MakeAddrLValue(
4234 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4235 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4236 SharedRefLValue.getTBAAInfo());
4237 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004238 if (Type->isArrayType()) {
4239 // Initialize firstprivate array.
4240 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4241 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004242 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004243 } else {
4244 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004245 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004246 CGF.EmitOMPAggregateAssign(
4247 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4248 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4249 Address SrcElement) {
4250 // Clean up any temporaries needed by the initialization.
4251 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4252 InitScope.addPrivate(
4253 Elem, [SrcElement]() -> Address { return SrcElement; });
4254 (void)InitScope.Privatize();
4255 // Emit initialization for single element.
4256 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4257 CGF, &CapturesInfo);
4258 CGF.EmitAnyExprToMem(Init, DestElement,
4259 Init->getType().getQualifiers(),
4260 /*IsInitializer=*/false);
4261 });
4262 }
4263 } else {
4264 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4265 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4266 return SharedRefLValue.getAddress();
4267 });
4268 (void)InitScope.Privatize();
4269 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4270 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4271 /*capturedByInit=*/false);
4272 }
4273 } else
4274 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4275 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004276 ++FI;
4277 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004278}
4279
4280/// Check if duplication function is required for taskloops.
4281static bool checkInitIsRequired(CodeGenFunction &CGF,
4282 ArrayRef<PrivateDataTy> Privates) {
4283 bool InitRequired = false;
4284 for (auto &&Pair : Privates) {
4285 auto *VD = Pair.second.PrivateCopy;
4286 auto *Init = VD->getAnyInitializer();
4287 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4288 !CGF.isTrivialInitializer(Init));
4289 }
4290 return InitRequired;
4291}
4292
4293
4294/// Emit task_dup function (for initialization of
4295/// private/firstprivate/lastprivate vars and last_iter flag)
4296/// \code
4297/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4298/// lastpriv) {
4299/// // setup lastprivate flag
4300/// task_dst->last = lastpriv;
4301/// // could be constructor calls here...
4302/// }
4303/// \endcode
4304static llvm::Value *
4305emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4306 const OMPExecutableDirective &D,
4307 QualType KmpTaskTWithPrivatesPtrQTy,
4308 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4309 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4310 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4311 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4312 auto &C = CGM.getContext();
4313 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004314 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4315 KmpTaskTWithPrivatesPtrQTy,
4316 ImplicitParamDecl::Other);
4317 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4318 KmpTaskTWithPrivatesPtrQTy,
4319 ImplicitParamDecl::Other);
4320 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4321 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004322 Args.push_back(&DstArg);
4323 Args.push_back(&SrcArg);
4324 Args.push_back(&LastprivArg);
4325 auto &TaskDupFnInfo =
4326 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4327 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4328 auto *TaskDup =
4329 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4330 ".omp_task_dup.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004331 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004332 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004333 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4334 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004335
4336 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4337 CGF.GetAddrOfLocalVar(&DstArg),
4338 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4339 // task_dst->liter = lastpriv;
4340 if (WithLastIter) {
4341 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4342 LValue Base = CGF.EmitLValueForField(
4343 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4344 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4345 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4346 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4347 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4348 }
4349
4350 // Emit initial values for private copies (if any).
4351 assert(!Privates.empty());
4352 Address KmpTaskSharedsPtr = Address::invalid();
4353 if (!Data.FirstprivateVars.empty()) {
4354 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4355 CGF.GetAddrOfLocalVar(&SrcArg),
4356 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4357 LValue Base = CGF.EmitLValueForField(
4358 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4359 KmpTaskSharedsPtr = Address(
4360 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4361 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4362 KmpTaskTShareds)),
4363 Loc),
4364 CGF.getNaturalTypeAlignment(SharedsTy));
4365 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004366 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4367 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004368 CGF.FinishFunction();
4369 return TaskDup;
4370}
4371
Alexey Bataev8a831592016-05-10 10:36:51 +00004372/// Checks if destructor function is required to be generated.
4373/// \return true if cleanups are required, false otherwise.
4374static bool
4375checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4376 bool NeedsCleanup = false;
4377 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4378 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4379 for (auto *FD : PrivateRD->fields()) {
4380 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4381 if (NeedsCleanup)
4382 break;
4383 }
4384 return NeedsCleanup;
4385}
4386
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004387CGOpenMPRuntime::TaskResultTy
4388CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4389 const OMPExecutableDirective &D,
4390 llvm::Value *TaskFunction, QualType SharedsTy,
4391 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004392 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004393 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004394 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004395 auto I = Data.PrivateCopies.begin();
4396 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004397 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4398 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004399 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004400 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4401 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004402 ++I;
4403 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004404 I = Data.FirstprivateCopies.begin();
4405 auto IElemInitRef = Data.FirstprivateInits.begin();
4406 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004407 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4408 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004409 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004410 PrivateHelpersTy(
4411 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4412 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004413 ++I;
4414 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004415 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004416 I = Data.LastprivateCopies.begin();
4417 for (auto *E : Data.LastprivateVars) {
4418 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4419 Privates.push_back(std::make_pair(
4420 C.getDeclAlign(VD),
4421 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4422 /*PrivateElemInit=*/nullptr)));
4423 ++I;
4424 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004425 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004426 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4427 // Build type kmp_routine_entry_t (if not built yet).
4428 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004429 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004430 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4431 if (SavedKmpTaskloopTQTy.isNull()) {
4432 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4433 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4434 }
4435 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004436 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004437 assert((D.getDirectiveKind() == OMPD_task ||
4438 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4439 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4440 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004441 if (SavedKmpTaskTQTy.isNull()) {
4442 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4443 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4444 }
4445 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004446 }
4447 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004448 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004449 auto *KmpTaskTWithPrivatesQTyRD =
4450 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4451 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4452 QualType KmpTaskTWithPrivatesPtrQTy =
4453 C.getPointerType(KmpTaskTWithPrivatesQTy);
4454 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4455 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004456 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004457 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4458
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004459 // Emit initial values for private copies (if any).
4460 llvm::Value *TaskPrivatesMap = nullptr;
4461 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004462 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004463 if (!Privates.empty()) {
4464 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004465 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4466 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4467 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004468 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4469 TaskPrivatesMap, TaskPrivatesMapTy);
4470 } else {
4471 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4472 cast<llvm::PointerType>(TaskPrivatesMapTy));
4473 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004474 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4475 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004476 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004477 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4478 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4479 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004480
4481 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4482 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4483 // kmp_routine_entry_t *task_entry);
4484 // Task flags. Format is taken from
4485 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4486 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004487 enum {
4488 TiedFlag = 0x1,
4489 FinalFlag = 0x2,
4490 DestructorsFlag = 0x8,
4491 PriorityFlag = 0x20
4492 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004493 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004494 bool NeedsCleanup = false;
4495 if (!Privates.empty()) {
4496 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4497 if (NeedsCleanup)
4498 Flags = Flags | DestructorsFlag;
4499 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004500 if (Data.Priority.getInt())
4501 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004502 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004503 Data.Final.getPointer()
4504 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004505 CGF.Builder.getInt32(FinalFlag),
4506 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004507 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004508 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004509 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004510 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4511 getThreadID(CGF, Loc), TaskFlags,
4512 KmpTaskTWithPrivatesTySize, SharedsSize,
4513 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4514 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004515 auto *NewTask = CGF.EmitRuntimeCall(
4516 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004517 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4518 NewTask, KmpTaskTWithPrivatesPtrTy);
4519 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4520 KmpTaskTWithPrivatesQTy);
4521 LValue TDBase =
4522 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004523 // Fill the data in the resulting kmp_task_t record.
4524 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004525 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004526 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004527 KmpTaskSharedsPtr =
4528 Address(CGF.EmitLoadOfScalar(
4529 CGF.EmitLValueForField(
4530 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4531 KmpTaskTShareds)),
4532 Loc),
4533 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004534 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4535 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
4536 CGF.EmitAggregateCopy(Dest, Src, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004537 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004538 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004539 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004540 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004541 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4542 SharedsTy, SharedsPtrTy, Data, Privates,
4543 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004544 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4545 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4546 Result.TaskDupFn = emitTaskDupFunction(
4547 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4548 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4549 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004550 }
4551 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004552 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4553 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004554 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004555 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4556 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4557 if (NeedsCleanup) {
4558 llvm::Value *DestructorFn = emitDestructorsFunction(
4559 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4560 KmpTaskTWithPrivatesQTy);
4561 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4562 LValue DestructorsLV = CGF.EmitLValueForField(
4563 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4564 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4565 DestructorFn, KmpRoutineEntryPtrTy),
4566 DestructorsLV);
4567 }
4568 // Set priority.
4569 if (Data.Priority.getInt()) {
4570 LValue Data2LV = CGF.EmitLValueForField(
4571 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4572 LValue PriorityLV = CGF.EmitLValueForField(
4573 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4574 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4575 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004576 Result.NewTask = NewTask;
4577 Result.TaskEntry = TaskEntry;
4578 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4579 Result.TDBase = TDBase;
4580 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4581 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004582}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004583
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004584void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4585 const OMPExecutableDirective &D,
4586 llvm::Value *TaskFunction,
4587 QualType SharedsTy, Address Shareds,
4588 const Expr *IfCond,
4589 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004590 if (!CGF.HaveInsertPoint())
4591 return;
4592
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004593 TaskResultTy Result =
4594 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4595 llvm::Value *NewTask = Result.NewTask;
4596 llvm::Value *TaskEntry = Result.TaskEntry;
4597 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4598 LValue TDBase = Result.TDBase;
4599 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004600 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004601 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004602 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004603 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004604 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004605 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004606 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004607 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4608 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004609 QualType FlagsTy =
4610 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004611 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4612 if (KmpDependInfoTy.isNull()) {
4613 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4614 KmpDependInfoRD->startDefinition();
4615 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4616 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4617 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4618 KmpDependInfoRD->completeDefinition();
4619 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004620 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004621 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004622 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004623 // Define type kmp_depend_info[<Dependences.size()>];
4624 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004625 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004626 ArrayType::Normal, /*IndexTypeQuals=*/0);
4627 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004628 DependenciesArray =
4629 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004630 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004631 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004632 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004633 llvm::Value *Size;
4634 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004635 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4636 LValue UpAddrLVal =
4637 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4638 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004639 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004640 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004641 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004642 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4643 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004644 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004645 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004646 auto Base = CGF.MakeAddrLValue(
4647 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004648 KmpDependInfoTy);
4649 // deps[i].base_addr = &<Dependences[i].second>;
4650 auto BaseAddrLVal = CGF.EmitLValueForField(
4651 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004652 CGF.EmitStoreOfScalar(
4653 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4654 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004655 // deps[i].len = sizeof(<Dependences[i].second>);
4656 auto LenLVal = CGF.EmitLValueForField(
4657 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4658 CGF.EmitStoreOfScalar(Size, LenLVal);
4659 // deps[i].flags = <Dependences[i].first>;
4660 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004661 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004662 case OMPC_DEPEND_in:
4663 DepKind = DepIn;
4664 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004665 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004666 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004667 case OMPC_DEPEND_inout:
4668 DepKind = DepInOut;
4669 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004670 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004671 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004672 case OMPC_DEPEND_unknown:
4673 llvm_unreachable("Unknown task dependence type");
4674 }
4675 auto FlagsLVal = CGF.EmitLValueForField(
4676 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4677 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4678 FlagsLVal);
4679 }
John McCall7f416cc2015-09-08 08:05:57 +00004680 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4681 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004682 CGF.VoidPtrTy);
4683 }
4684
Alexey Bataev62b63b12015-03-10 07:28:44 +00004685 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4686 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004687 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4688 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4689 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4690 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004691 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004692 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004693 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4694 llvm::Value *DepTaskArgs[7];
4695 if (NumDependencies) {
4696 DepTaskArgs[0] = UpLoc;
4697 DepTaskArgs[1] = ThreadID;
4698 DepTaskArgs[2] = NewTask;
4699 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4700 DepTaskArgs[4] = DependenciesArray.getPointer();
4701 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4702 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4703 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004704 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4705 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004706 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004707 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004708 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4709 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4710 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4711 }
John McCall7f416cc2015-09-08 08:05:57 +00004712 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004713 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004714 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004715 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004716 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004717 TaskArgs);
4718 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004719 // Check if parent region is untied and build return for untied task;
4720 if (auto *Region =
4721 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4722 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004723 };
John McCall7f416cc2015-09-08 08:05:57 +00004724
4725 llvm::Value *DepWaitTaskArgs[6];
4726 if (NumDependencies) {
4727 DepWaitTaskArgs[0] = UpLoc;
4728 DepWaitTaskArgs[1] = ThreadID;
4729 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4730 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4731 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4732 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4733 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004734 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004735 NumDependencies, &DepWaitTaskArgs,
4736 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004737 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004738 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4739 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4740 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4741 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4742 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004743 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004744 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004745 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004746 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004747 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4748 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004749 Action.Enter(CGF);
4750 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004751 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004752 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004753 };
4754
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004755 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4756 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004757 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4758 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004759 RegionCodeGenTy RCG(CodeGen);
4760 CommonActionTy Action(
4761 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4762 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4763 RCG.setAction(Action);
4764 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004765 };
John McCall7f416cc2015-09-08 08:05:57 +00004766
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004767 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004768 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004769 else {
4770 RegionCodeGenTy ThenRCG(ThenCodeGen);
4771 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004772 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004773}
4774
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004775void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4776 const OMPLoopDirective &D,
4777 llvm::Value *TaskFunction,
4778 QualType SharedsTy, Address Shareds,
4779 const Expr *IfCond,
4780 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004781 if (!CGF.HaveInsertPoint())
4782 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004783 TaskResultTy Result =
4784 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004785 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4786 // libcall.
4787 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4788 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4789 // sched, kmp_uint64 grainsize, void *task_dup);
4790 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4791 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4792 llvm::Value *IfVal;
4793 if (IfCond) {
4794 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4795 /*isSigned=*/true);
4796 } else
4797 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4798
4799 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004800 Result.TDBase,
4801 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004802 auto *LBVar =
4803 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4804 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4805 /*IsInitializer=*/true);
4806 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004807 Result.TDBase,
4808 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004809 auto *UBVar =
4810 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4811 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4812 /*IsInitializer=*/true);
4813 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004814 Result.TDBase,
4815 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004816 auto *StVar =
4817 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4818 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4819 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004820 // Store reductions address.
4821 LValue RedLVal = CGF.EmitLValueForField(
4822 Result.TDBase,
4823 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4824 if (Data.Reductions)
4825 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4826 else {
4827 CGF.EmitNullInitialization(RedLVal.getAddress(),
4828 CGF.getContext().VoidPtrTy);
4829 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004830 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004831 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004832 UpLoc,
4833 ThreadID,
4834 Result.NewTask,
4835 IfVal,
4836 LBLVal.getPointer(),
4837 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004838 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00004839 llvm::ConstantInt::getNullValue(
4840 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004841 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004842 CGF.IntTy, Data.Schedule.getPointer()
4843 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004844 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004845 Data.Schedule.getPointer()
4846 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004847 /*isSigned=*/false)
4848 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004849 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4850 Result.TaskDupFn, CGF.VoidPtrTy)
4851 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004852 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4853}
4854
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004855/// \brief Emit reduction operation for each element of array (required for
4856/// array sections) LHS op = RHS.
4857/// \param Type Type of array.
4858/// \param LHSVar Variable on the left side of the reduction operation
4859/// (references element of array in original variable).
4860/// \param RHSVar Variable on the right side of the reduction operation
4861/// (references element of array in original variable).
4862/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4863/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004864static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004865 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4866 const VarDecl *RHSVar,
4867 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4868 const Expr *, const Expr *)> &RedOpGen,
4869 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4870 const Expr *UpExpr = nullptr) {
4871 // Perform element-by-element initialization.
4872 QualType ElementTy;
4873 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4874 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4875
4876 // Drill down to the base element type on both arrays.
4877 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4878 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4879
4880 auto RHSBegin = RHSAddr.getPointer();
4881 auto LHSBegin = LHSAddr.getPointer();
4882 // Cast from pointer to array type to pointer to single element.
4883 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4884 // The basic structure here is a while-do loop.
4885 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4886 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4887 auto IsEmpty =
4888 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4889 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4890
4891 // Enter the loop body, making that address the current address.
4892 auto EntryBB = CGF.Builder.GetInsertBlock();
4893 CGF.EmitBlock(BodyBB);
4894
4895 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4896
4897 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4898 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4899 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4900 Address RHSElementCurrent =
4901 Address(RHSElementPHI,
4902 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4903
4904 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4905 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4906 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4907 Address LHSElementCurrent =
4908 Address(LHSElementPHI,
4909 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4910
4911 // Emit copy.
4912 CodeGenFunction::OMPPrivateScope Scope(CGF);
4913 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4914 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4915 Scope.Privatize();
4916 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4917 Scope.ForceCleanup();
4918
4919 // Shift the address forward by one element.
4920 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4921 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4922 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4923 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4924 // Check whether we've reached the end.
4925 auto Done =
4926 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4927 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4928 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4929 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4930
4931 // Done.
4932 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4933}
4934
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004935/// Emit reduction combiner. If the combiner is a simple expression emit it as
4936/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4937/// UDR combiner function.
4938static void emitReductionCombiner(CodeGenFunction &CGF,
4939 const Expr *ReductionOp) {
4940 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4941 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4942 if (auto *DRE =
4943 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4944 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4945 std::pair<llvm::Function *, llvm::Function *> Reduction =
4946 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4947 RValue Func = RValue::get(Reduction.first);
4948 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4949 CGF.EmitIgnoredExpr(ReductionOp);
4950 return;
4951 }
4952 CGF.EmitIgnoredExpr(ReductionOp);
4953}
4954
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004955llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004956 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
4957 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
4958 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004959 auto &C = CGM.getContext();
4960
4961 // void reduction_func(void *LHSArg, void *RHSArg);
4962 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004963 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
4964 ImplicitParamDecl::Other);
4965 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
4966 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004967 Args.push_back(&LHSArg);
4968 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004969 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004970 auto *Fn = llvm::Function::Create(
4971 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4972 ".omp.reduction.reduction_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004973 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004974 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004975 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004976
4977 // Dst = (void*[n])(LHSArg);
4978 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004979 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4980 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4981 ArgsType), CGF.getPointerAlign());
4982 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4983 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4984 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004985
4986 // ...
4987 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4988 // ...
4989 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004990 auto IPriv = Privates.begin();
4991 unsigned Idx = 0;
4992 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004993 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4994 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004995 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004996 });
4997 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4998 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004999 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005000 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005001 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005002 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005003 // Get array size and emit VLA type.
5004 ++Idx;
5005 Address Elem =
5006 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5007 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005008 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
5009 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005010 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005011 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005012 CGF.EmitVariablyModifiedType(PrivTy);
5013 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005014 }
5015 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005016 IPriv = Privates.begin();
5017 auto ILHS = LHSExprs.begin();
5018 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005019 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005020 if ((*IPriv)->getType()->isArrayType()) {
5021 // Emit reduction for array section.
5022 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5023 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005024 EmitOMPAggregateReduction(
5025 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5026 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5027 emitReductionCombiner(CGF, E);
5028 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005029 } else
5030 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005031 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00005032 ++IPriv;
5033 ++ILHS;
5034 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005035 }
5036 Scope.ForceCleanup();
5037 CGF.FinishFunction();
5038 return Fn;
5039}
5040
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005041void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5042 const Expr *ReductionOp,
5043 const Expr *PrivateRef,
5044 const DeclRefExpr *LHS,
5045 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005046 if (PrivateRef->getType()->isArrayType()) {
5047 // Emit reduction for array section.
5048 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5049 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5050 EmitOMPAggregateReduction(
5051 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5052 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5053 emitReductionCombiner(CGF, ReductionOp);
5054 });
5055 } else
5056 // Emit reduction for array subscript or single variable.
5057 emitReductionCombiner(CGF, ReductionOp);
5058}
5059
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005060void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005061 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005062 ArrayRef<const Expr *> LHSExprs,
5063 ArrayRef<const Expr *> RHSExprs,
5064 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005065 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005066 if (!CGF.HaveInsertPoint())
5067 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005068
5069 bool WithNowait = Options.WithNowait;
5070 bool SimpleReduction = Options.SimpleReduction;
5071
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005072 // Next code should be emitted for reduction:
5073 //
5074 // static kmp_critical_name lock = { 0 };
5075 //
5076 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5077 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5078 // ...
5079 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5080 // *(Type<n>-1*)rhs[<n>-1]);
5081 // }
5082 //
5083 // ...
5084 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5085 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5086 // RedList, reduce_func, &<lock>)) {
5087 // case 1:
5088 // ...
5089 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5090 // ...
5091 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5092 // break;
5093 // case 2:
5094 // ...
5095 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5096 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005097 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005098 // break;
5099 // default:;
5100 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005101 //
5102 // if SimpleReduction is true, only the next code is generated:
5103 // ...
5104 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5105 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005106
5107 auto &C = CGM.getContext();
5108
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005109 if (SimpleReduction) {
5110 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005111 auto IPriv = Privates.begin();
5112 auto ILHS = LHSExprs.begin();
5113 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005114 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005115 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5116 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005117 ++IPriv;
5118 ++ILHS;
5119 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005120 }
5121 return;
5122 }
5123
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005124 // 1. Build a list of reduction variables.
5125 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005126 auto Size = RHSExprs.size();
5127 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005128 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005129 // Reserve place for array size.
5130 ++Size;
5131 }
5132 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005133 QualType ReductionArrayTy =
5134 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5135 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005136 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005137 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005138 auto IPriv = Privates.begin();
5139 unsigned Idx = 0;
5140 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005141 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005142 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005143 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005144 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005145 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5146 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005147 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005148 // Store array size.
5149 ++Idx;
5150 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5151 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005152 llvm::Value *Size = CGF.Builder.CreateIntCast(
5153 CGF.getVLASize(
5154 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005155 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005156 CGF.SizeTy, /*isSigned=*/false);
5157 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5158 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005159 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005160 }
5161
5162 // 2. Emit reduce_func().
5163 auto *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005164 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5165 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005166
5167 // 3. Create static kmp_critical_name lock = { 0 };
5168 auto *Lock = getCriticalRegionLock(".reduction");
5169
5170 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5171 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005172 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005173 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005174 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005175 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5176 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005177 llvm::Value *Args[] = {
5178 IdentTLoc, // ident_t *<loc>
5179 ThreadId, // i32 <gtid>
5180 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5181 ReductionArrayTySize, // size_type sizeof(RedList)
5182 RL, // void *RedList
5183 ReductionFn, // void (*) (void *, void *) <reduce_func>
5184 Lock // kmp_critical_name *&<lock>
5185 };
5186 auto Res = CGF.EmitRuntimeCall(
5187 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5188 : OMPRTL__kmpc_reduce),
5189 Args);
5190
5191 // 5. Build switch(res)
5192 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5193 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5194
5195 // 6. Build case 1:
5196 // ...
5197 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5198 // ...
5199 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5200 // break;
5201 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5202 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5203 CGF.EmitBlock(Case1BB);
5204
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005205 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5206 llvm::Value *EndArgs[] = {
5207 IdentTLoc, // ident_t *<loc>
5208 ThreadId, // i32 <gtid>
5209 Lock // kmp_critical_name *&<lock>
5210 };
5211 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5212 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005213 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005214 auto IPriv = Privates.begin();
5215 auto ILHS = LHSExprs.begin();
5216 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005217 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005218 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5219 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005220 ++IPriv;
5221 ++ILHS;
5222 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005223 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005224 };
5225 RegionCodeGenTy RCG(CodeGen);
5226 CommonActionTy Action(
5227 nullptr, llvm::None,
5228 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5229 : OMPRTL__kmpc_end_reduce),
5230 EndArgs);
5231 RCG.setAction(Action);
5232 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005233
5234 CGF.EmitBranch(DefaultBB);
5235
5236 // 7. Build case 2:
5237 // ...
5238 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5239 // ...
5240 // break;
5241 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5242 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5243 CGF.EmitBlock(Case2BB);
5244
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005245 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5246 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005247 auto ILHS = LHSExprs.begin();
5248 auto IRHS = RHSExprs.begin();
5249 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005250 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005251 const Expr *XExpr = nullptr;
5252 const Expr *EExpr = nullptr;
5253 const Expr *UpExpr = nullptr;
5254 BinaryOperatorKind BO = BO_Comma;
5255 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5256 if (BO->getOpcode() == BO_Assign) {
5257 XExpr = BO->getLHS();
5258 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005259 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005260 }
5261 // Try to emit update expression as a simple atomic.
5262 auto *RHSExpr = UpExpr;
5263 if (RHSExpr) {
5264 // Analyze RHS part of the whole expression.
5265 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5266 RHSExpr->IgnoreParenImpCasts())) {
5267 // If this is a conditional operator, analyze its condition for
5268 // min/max reduction operator.
5269 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005270 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005271 if (auto *BORHS =
5272 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5273 EExpr = BORHS->getRHS();
5274 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005275 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005276 }
5277 if (XExpr) {
5278 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005279 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005280 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5281 const Expr *EExpr, const Expr *UpExpr) {
5282 LValue X = CGF.EmitLValue(XExpr);
5283 RValue E;
5284 if (EExpr)
5285 E = CGF.EmitAnyExpr(EExpr);
5286 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005287 X, E, BO, /*IsXLHSInRHSPart=*/true,
5288 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005289 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005290 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5291 PrivateScope.addPrivate(
5292 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5293 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5294 CGF.emitOMPSimpleStore(
5295 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5296 VD->getType().getNonReferenceType(), Loc);
5297 return LHSTemp;
5298 });
5299 (void)PrivateScope.Privatize();
5300 return CGF.EmitAnyExpr(UpExpr);
5301 });
5302 };
5303 if ((*IPriv)->getType()->isArrayType()) {
5304 // Emit atomic reduction for array section.
5305 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5306 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5307 AtomicRedGen, XExpr, EExpr, UpExpr);
5308 } else
5309 // Emit atomic reduction for array subscript or single variable.
5310 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5311 } else {
5312 // Emit as a critical region.
5313 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5314 const Expr *, const Expr *) {
5315 auto &RT = CGF.CGM.getOpenMPRuntime();
5316 RT.emitCriticalRegion(
5317 CGF, ".atomic_reduction",
5318 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5319 Action.Enter(CGF);
5320 emitReductionCombiner(CGF, E);
5321 },
5322 Loc);
5323 };
5324 if ((*IPriv)->getType()->isArrayType()) {
5325 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5326 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5327 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5328 CritRedGen);
5329 } else
5330 CritRedGen(CGF, nullptr, nullptr, nullptr);
5331 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005332 ++ILHS;
5333 ++IRHS;
5334 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005335 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005336 };
5337 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5338 if (!WithNowait) {
5339 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5340 llvm::Value *EndArgs[] = {
5341 IdentTLoc, // ident_t *<loc>
5342 ThreadId, // i32 <gtid>
5343 Lock // kmp_critical_name *&<lock>
5344 };
5345 CommonActionTy Action(nullptr, llvm::None,
5346 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5347 EndArgs);
5348 AtomicRCG.setAction(Action);
5349 AtomicRCG(CGF);
5350 } else
5351 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005352
5353 CGF.EmitBranch(DefaultBB);
5354 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5355}
5356
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005357/// Generates unique name for artificial threadprivate variables.
5358/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5359static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5360 unsigned N) {
5361 SmallString<256> Buffer;
5362 llvm::raw_svector_ostream Out(Buffer);
5363 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5364 return Out.str();
5365}
5366
5367/// Emits reduction initializer function:
5368/// \code
5369/// void @.red_init(void* %arg) {
5370/// %0 = bitcast void* %arg to <type>*
5371/// store <type> <init>, <type>* %0
5372/// ret void
5373/// }
5374/// \endcode
5375static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5376 SourceLocation Loc,
5377 ReductionCodeGen &RCG, unsigned N) {
5378 auto &C = CGM.getContext();
5379 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005380 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5381 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005382 Args.emplace_back(&Param);
5383 auto &FnInfo =
5384 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5385 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5386 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5387 ".red_init.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005388 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005389 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005390 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005391 Address PrivateAddr = CGF.EmitLoadOfPointer(
5392 CGF.GetAddrOfLocalVar(&Param),
5393 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5394 llvm::Value *Size = nullptr;
5395 // If the size of the reduction item is non-constant, load it from global
5396 // threadprivate variable.
5397 if (RCG.getSizes(N).second) {
5398 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5399 CGF, CGM.getContext().getSizeType(),
5400 generateUniqueName("reduction_size", Loc, N));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005401 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5402 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005403 }
5404 RCG.emitAggregateType(CGF, N, Size);
5405 LValue SharedLVal;
5406 // If initializer uses initializer from declare reduction construct, emit a
5407 // pointer to the address of the original reduction item (reuired by reduction
5408 // initializer)
5409 if (RCG.usesReductionInitializer(N)) {
5410 Address SharedAddr =
5411 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5412 CGF, CGM.getContext().VoidPtrTy,
5413 generateUniqueName("reduction", Loc, N));
5414 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5415 } else {
5416 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5417 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5418 CGM.getContext().VoidPtrTy);
5419 }
5420 // Emit the initializer:
5421 // %0 = bitcast void* %arg to <type>*
5422 // store <type> <init>, <type>* %0
5423 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5424 [](CodeGenFunction &) { return false; });
5425 CGF.FinishFunction();
5426 return Fn;
5427}
5428
5429/// Emits reduction combiner function:
5430/// \code
5431/// void @.red_comb(void* %arg0, void* %arg1) {
5432/// %lhs = bitcast void* %arg0 to <type>*
5433/// %rhs = bitcast void* %arg1 to <type>*
5434/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5435/// store <type> %2, <type>* %lhs
5436/// ret void
5437/// }
5438/// \endcode
5439static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5440 SourceLocation Loc,
5441 ReductionCodeGen &RCG, unsigned N,
5442 const Expr *ReductionOp,
5443 const Expr *LHS, const Expr *RHS,
5444 const Expr *PrivateRef) {
5445 auto &C = CGM.getContext();
5446 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5447 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5448 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005449 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5450 C.VoidPtrTy, ImplicitParamDecl::Other);
5451 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5452 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005453 Args.emplace_back(&ParamInOut);
5454 Args.emplace_back(&ParamIn);
5455 auto &FnInfo =
5456 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5457 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5458 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5459 ".red_comb.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005460 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005461 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005462 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005463 llvm::Value *Size = nullptr;
5464 // If the size of the reduction item is non-constant, load it from global
5465 // threadprivate variable.
5466 if (RCG.getSizes(N).second) {
5467 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5468 CGF, CGM.getContext().getSizeType(),
5469 generateUniqueName("reduction_size", Loc, N));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005470 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5471 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005472 }
5473 RCG.emitAggregateType(CGF, N, Size);
5474 // Remap lhs and rhs variables to the addresses of the function arguments.
5475 // %lhs = bitcast void* %arg0 to <type>*
5476 // %rhs = bitcast void* %arg1 to <type>*
5477 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5478 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5479 // Pull out the pointer to the variable.
5480 Address PtrAddr = CGF.EmitLoadOfPointer(
5481 CGF.GetAddrOfLocalVar(&ParamInOut),
5482 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5483 return CGF.Builder.CreateElementBitCast(
5484 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5485 });
5486 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5487 // Pull out the pointer to the variable.
5488 Address PtrAddr = CGF.EmitLoadOfPointer(
5489 CGF.GetAddrOfLocalVar(&ParamIn),
5490 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5491 return CGF.Builder.CreateElementBitCast(
5492 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5493 });
5494 PrivateScope.Privatize();
5495 // Emit the combiner body:
5496 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5497 // store <type> %2, <type>* %lhs
5498 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5499 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5500 cast<DeclRefExpr>(RHS));
5501 CGF.FinishFunction();
5502 return Fn;
5503}
5504
5505/// Emits reduction finalizer function:
5506/// \code
5507/// void @.red_fini(void* %arg) {
5508/// %0 = bitcast void* %arg to <type>*
5509/// <destroy>(<type>* %0)
5510/// ret void
5511/// }
5512/// \endcode
5513static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5514 SourceLocation Loc,
5515 ReductionCodeGen &RCG, unsigned N) {
5516 if (!RCG.needCleanups(N))
5517 return nullptr;
5518 auto &C = CGM.getContext();
5519 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005520 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5521 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005522 Args.emplace_back(&Param);
5523 auto &FnInfo =
5524 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5525 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5526 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5527 ".red_fini.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005528 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005529 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005530 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005531 Address PrivateAddr = CGF.EmitLoadOfPointer(
5532 CGF.GetAddrOfLocalVar(&Param),
5533 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5534 llvm::Value *Size = nullptr;
5535 // If the size of the reduction item is non-constant, load it from global
5536 // threadprivate variable.
5537 if (RCG.getSizes(N).second) {
5538 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5539 CGF, CGM.getContext().getSizeType(),
5540 generateUniqueName("reduction_size", Loc, N));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005541 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5542 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005543 }
5544 RCG.emitAggregateType(CGF, N, Size);
5545 // Emit the finalizer body:
5546 // <destroy>(<type>* %0)
5547 RCG.emitCleanups(CGF, N, PrivateAddr);
5548 CGF.FinishFunction();
5549 return Fn;
5550}
5551
5552llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5553 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5554 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5555 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5556 return nullptr;
5557
5558 // Build typedef struct:
5559 // kmp_task_red_input {
5560 // void *reduce_shar; // shared reduction item
5561 // size_t reduce_size; // size of data item
5562 // void *reduce_init; // data initialization routine
5563 // void *reduce_fini; // data finalization routine
5564 // void *reduce_comb; // data combiner routine
5565 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5566 // } kmp_task_red_input_t;
5567 ASTContext &C = CGM.getContext();
5568 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5569 RD->startDefinition();
5570 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5571 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5572 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5573 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5574 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5575 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5576 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5577 RD->completeDefinition();
5578 QualType RDType = C.getRecordType(RD);
5579 unsigned Size = Data.ReductionVars.size();
5580 llvm::APInt ArraySize(/*numBits=*/64, Size);
5581 QualType ArrayRDType = C.getConstantArrayType(
5582 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5583 // kmp_task_red_input_t .rd_input.[Size];
5584 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5585 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5586 Data.ReductionOps);
5587 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5588 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5589 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5590 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5591 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5592 TaskRedInput.getPointer(), Idxs,
5593 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5594 ".rd_input.gep.");
5595 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5596 // ElemLVal.reduce_shar = &Shareds[Cnt];
5597 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5598 RCG.emitSharedLValue(CGF, Cnt);
5599 llvm::Value *CastedShared =
5600 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5601 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5602 RCG.emitAggregateType(CGF, Cnt);
5603 llvm::Value *SizeValInChars;
5604 llvm::Value *SizeVal;
5605 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5606 // We use delayed creation/initialization for VLAs, array sections and
5607 // custom reduction initializations. It is required because runtime does not
5608 // provide the way to pass the sizes of VLAs/array sections to
5609 // initializer/combiner/finalizer functions and does not pass the pointer to
5610 // original reduction item to the initializer. Instead threadprivate global
5611 // variables are used to store these values and use them in the functions.
5612 bool DelayedCreation = !!SizeVal;
5613 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5614 /*isSigned=*/false);
5615 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5616 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5617 // ElemLVal.reduce_init = init;
5618 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5619 llvm::Value *InitAddr =
5620 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5621 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5622 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5623 // ElemLVal.reduce_fini = fini;
5624 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5625 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5626 llvm::Value *FiniAddr = Fini
5627 ? CGF.EmitCastToVoidPtr(Fini)
5628 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5629 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5630 // ElemLVal.reduce_comb = comb;
5631 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5632 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5633 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5634 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5635 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5636 // ElemLVal.flags = 0;
5637 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5638 if (DelayedCreation) {
5639 CGF.EmitStoreOfScalar(
5640 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5641 FlagsLVal);
5642 } else
5643 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5644 }
5645 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5646 // *data);
5647 llvm::Value *Args[] = {
5648 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5649 /*isSigned=*/true),
5650 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5651 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5652 CGM.VoidPtrTy)};
5653 return CGF.EmitRuntimeCall(
5654 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5655}
5656
5657void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5658 SourceLocation Loc,
5659 ReductionCodeGen &RCG,
5660 unsigned N) {
5661 auto Sizes = RCG.getSizes(N);
5662 // Emit threadprivate global variable if the type is non-constant
5663 // (Sizes.second = nullptr).
5664 if (Sizes.second) {
5665 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5666 /*isSigned=*/false);
5667 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5668 CGF, CGM.getContext().getSizeType(),
5669 generateUniqueName("reduction_size", Loc, N));
5670 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5671 }
5672 // Store address of the original reduction item if custom initializer is used.
5673 if (RCG.usesReductionInitializer(N)) {
5674 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5675 CGF, CGM.getContext().VoidPtrTy,
5676 generateUniqueName("reduction", Loc, N));
5677 CGF.Builder.CreateStore(
5678 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5679 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5680 SharedAddr, /*IsVolatile=*/false);
5681 }
5682}
5683
5684Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5685 SourceLocation Loc,
5686 llvm::Value *ReductionsPtr,
5687 LValue SharedLVal) {
5688 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5689 // *d);
5690 llvm::Value *Args[] = {
5691 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5692 /*isSigned=*/true),
5693 ReductionsPtr,
5694 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5695 CGM.VoidPtrTy)};
5696 return Address(
5697 CGF.EmitRuntimeCall(
5698 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5699 SharedLVal.getAlignment());
5700}
5701
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005702void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5703 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005704 if (!CGF.HaveInsertPoint())
5705 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005706 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5707 // global_tid);
5708 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5709 // Ignore return result until untied tasks are supported.
5710 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005711 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5712 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005713}
5714
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005715void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005716 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005717 const RegionCodeGenTy &CodeGen,
5718 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005719 if (!CGF.HaveInsertPoint())
5720 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005721 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005722 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005723}
5724
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005725namespace {
5726enum RTCancelKind {
5727 CancelNoreq = 0,
5728 CancelParallel = 1,
5729 CancelLoop = 2,
5730 CancelSections = 3,
5731 CancelTaskgroup = 4
5732};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005733} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005734
5735static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5736 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005737 if (CancelRegion == OMPD_parallel)
5738 CancelKind = CancelParallel;
5739 else if (CancelRegion == OMPD_for)
5740 CancelKind = CancelLoop;
5741 else if (CancelRegion == OMPD_sections)
5742 CancelKind = CancelSections;
5743 else {
5744 assert(CancelRegion == OMPD_taskgroup);
5745 CancelKind = CancelTaskgroup;
5746 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005747 return CancelKind;
5748}
5749
5750void CGOpenMPRuntime::emitCancellationPointCall(
5751 CodeGenFunction &CGF, SourceLocation Loc,
5752 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005753 if (!CGF.HaveInsertPoint())
5754 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005755 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5756 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005757 if (auto *OMPRegionInfo =
5758 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005759 // For 'cancellation point taskgroup', the task region info may not have a
5760 // cancel. This may instead happen in another adjacent task.
5761 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005762 llvm::Value *Args[] = {
5763 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5764 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005765 // Ignore return result until untied tasks are supported.
5766 auto *Result = CGF.EmitRuntimeCall(
5767 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5768 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005769 // exit from construct;
5770 // }
5771 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5772 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5773 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5774 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5775 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005776 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005777 auto CancelDest =
5778 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005779 CGF.EmitBranchThroughCleanup(CancelDest);
5780 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5781 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005782 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005783}
5784
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005785void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005786 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005787 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005788 if (!CGF.HaveInsertPoint())
5789 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005790 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5791 // kmp_int32 cncl_kind);
5792 if (auto *OMPRegionInfo =
5793 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005794 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5795 PrePostActionTy &) {
5796 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005797 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005798 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005799 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5800 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005801 auto *Result = CGF.EmitRuntimeCall(
5802 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005803 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005804 // exit from construct;
5805 // }
5806 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5807 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5808 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5809 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5810 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005811 // exit from construct;
5812 auto CancelDest =
5813 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5814 CGF.EmitBranchThroughCleanup(CancelDest);
5815 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5816 };
5817 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005818 emitOMPIfClause(CGF, IfCond, ThenGen,
5819 [](CodeGenFunction &, PrePostActionTy &) {});
5820 else {
5821 RegionCodeGenTy ThenRCG(ThenGen);
5822 ThenRCG(CGF);
5823 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005824 }
5825}
Samuel Antaobed3c462015-10-02 16:14:20 +00005826
Samuel Antaoee8fb302016-01-06 13:42:12 +00005827/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005828/// consists of the file and device IDs as well as line number associated with
5829/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005830static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5831 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005832 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005833
5834 auto &SM = C.getSourceManager();
5835
5836 // The loc should be always valid and have a file ID (the user cannot use
5837 // #pragma directives in macros)
5838
5839 assert(Loc.isValid() && "Source location is expected to be always valid.");
5840 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5841
5842 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5843 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5844
5845 llvm::sys::fs::UniqueID ID;
5846 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5847 llvm_unreachable("Source file with target region no longer exists!");
5848
5849 DeviceID = ID.getDevice();
5850 FileID = ID.getFile();
5851 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005852}
5853
5854void CGOpenMPRuntime::emitTargetOutlinedFunction(
5855 const OMPExecutableDirective &D, StringRef ParentName,
5856 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005857 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005858 assert(!ParentName.empty() && "Invalid target region parent name!");
5859
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005860 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5861 IsOffloadEntry, CodeGen);
5862}
5863
5864void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5865 const OMPExecutableDirective &D, StringRef ParentName,
5866 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5867 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005868 // Create a unique name for the entry function using the source location
5869 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005870 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005871 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005872 //
5873 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005874 // mangled name of the function that encloses the target region and BB is the
5875 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005876
5877 unsigned DeviceID;
5878 unsigned FileID;
5879 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005880 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005881 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005882 SmallString<64> EntryFnName;
5883 {
5884 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005885 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5886 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005887 }
5888
Alexey Bataev475a7442018-01-12 19:39:11 +00005889 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005890
Samuel Antaobed3c462015-10-02 16:14:20 +00005891 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005892 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005893 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005894
Samuel Antao6d004262016-06-16 18:39:34 +00005895 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005896
5897 // If this target outline function is not an offload entry, we don't need to
5898 // register it.
5899 if (!IsOffloadEntry)
5900 return;
5901
5902 // The target region ID is used by the runtime library to identify the current
5903 // target region, so it only has to be unique and not necessarily point to
5904 // anything. It could be the pointer to the outlined function that implements
5905 // the target region, but we aren't using that so that the compiler doesn't
5906 // need to keep that, and could therefore inline the host function if proven
5907 // worthwhile during optimization. In the other hand, if emitting code for the
5908 // device, the ID has to be the function address so that it can retrieved from
5909 // the offloading entry and launched by the runtime library. We also mark the
5910 // outlined function to have external linkage in case we are emitting code for
5911 // the device, because these functions will be entry points to the device.
5912
5913 if (CGM.getLangOpts().OpenMPIsDevice) {
5914 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5915 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00005916 OutlinedFn->setDSOLocal(false);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005917 } else
5918 OutlinedFnID = new llvm::GlobalVariable(
5919 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5920 llvm::GlobalValue::PrivateLinkage,
5921 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5922
5923 // Register the information for the entry associated with this target region.
5924 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005925 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5926 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005927}
5928
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005929/// discard all CompoundStmts intervening between two constructs
5930static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5931 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5932 Body = CS->body_front();
5933
5934 return Body;
5935}
5936
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005937/// Emit the number of teams for a target directive. Inspect the num_teams
5938/// clause associated with a teams construct combined or closely nested
5939/// with the target directive.
5940///
5941/// Emit a team of size one for directives such as 'target parallel' that
5942/// have no associated teams construct.
5943///
5944/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005945static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005946emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5947 CodeGenFunction &CGF,
5948 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005949
5950 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5951 "teams directive expected to be "
5952 "emitted only for the host!");
5953
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005954 auto &Bld = CGF.Builder;
5955
5956 // If the target directive is combined with a teams directive:
5957 // Return the value in the num_teams clause, if any.
5958 // Otherwise, return 0 to denote the runtime default.
5959 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5960 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5961 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5962 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5963 /*IgnoreResultAssign*/ true);
5964 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5965 /*IsSigned=*/true);
5966 }
5967
5968 // The default value is 0.
5969 return Bld.getInt32(0);
5970 }
5971
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005972 // If the target directive is combined with a parallel directive but not a
5973 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005974 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5975 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005976
5977 // If the current target region has a teams region enclosed, we need to get
5978 // the number of teams to pass to the runtime function call. This is done
5979 // by generating the expression in a inlined region. This is required because
5980 // the expression is captured in the enclosing target environment when the
5981 // teams directive is not combined with target.
5982
Alexey Bataev475a7442018-01-12 19:39:11 +00005983 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005984
Alexey Bataev50a1c782017-12-01 21:31:08 +00005985 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005986 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00005987 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
5988 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5989 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5990 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5991 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
5992 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5993 /*IsSigned=*/true);
5994 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00005995
Alexey Bataev50a1c782017-12-01 21:31:08 +00005996 // If we have an enclosed teams directive but no num_teams clause we use
5997 // the default value 0.
5998 return Bld.getInt32(0);
5999 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006000 }
6001
6002 // No teams associated with the directive.
6003 return nullptr;
6004}
6005
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006006/// Emit the number of threads for a target directive. Inspect the
6007/// thread_limit clause associated with a teams construct combined or closely
6008/// nested with the target directive.
6009///
6010/// Emit the num_threads clause for directives such as 'target parallel' that
6011/// have no associated teams construct.
6012///
6013/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006014static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006015emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6016 CodeGenFunction &CGF,
6017 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006018
6019 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6020 "teams directive expected to be "
6021 "emitted only for the host!");
6022
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006023 auto &Bld = CGF.Builder;
6024
6025 //
6026 // If the target directive is combined with a teams directive:
6027 // Return the value in the thread_limit clause, if any.
6028 //
6029 // If the target directive is combined with a parallel directive:
6030 // Return the value in the num_threads clause, if any.
6031 //
6032 // If both clauses are set, select the minimum of the two.
6033 //
6034 // If neither teams or parallel combined directives set the number of threads
6035 // in a team, return 0 to denote the runtime default.
6036 //
6037 // If this is not a teams directive return nullptr.
6038
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006039 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6040 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006041 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6042 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006043 llvm::Value *ThreadLimitVal = nullptr;
6044
6045 if (const auto *ThreadLimitClause =
6046 D.getSingleClause<OMPThreadLimitClause>()) {
6047 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6048 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6049 /*IgnoreResultAssign*/ true);
6050 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6051 /*IsSigned=*/true);
6052 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006053
6054 if (const auto *NumThreadsClause =
6055 D.getSingleClause<OMPNumThreadsClause>()) {
6056 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6057 llvm::Value *NumThreads =
6058 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6059 /*IgnoreResultAssign*/ true);
6060 NumThreadsVal =
6061 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6062 }
6063
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006064 // Select the lesser of thread_limit and num_threads.
6065 if (NumThreadsVal)
6066 ThreadLimitVal = ThreadLimitVal
6067 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6068 ThreadLimitVal),
6069 NumThreadsVal, ThreadLimitVal)
6070 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006071
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006072 // Set default value passed to the runtime if either teams or a target
6073 // parallel type directive is found but no clause is specified.
6074 if (!ThreadLimitVal)
6075 ThreadLimitVal = DefaultThreadLimitVal;
6076
6077 return ThreadLimitVal;
6078 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006079
Samuel Antaob68e2db2016-03-03 16:20:23 +00006080 // If the current target region has a teams region enclosed, we need to get
6081 // the thread limit to pass to the runtime function call. This is done
6082 // by generating the expression in a inlined region. This is required because
6083 // the expression is captured in the enclosing target environment when the
6084 // teams directive is not combined with target.
6085
Alexey Bataev475a7442018-01-12 19:39:11 +00006086 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006087
Alexey Bataev50a1c782017-12-01 21:31:08 +00006088 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006089 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006090 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6091 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
6092 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6093 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6094 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6095 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6096 /*IsSigned=*/true);
6097 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006098
Alexey Bataev50a1c782017-12-01 21:31:08 +00006099 // If we have an enclosed teams directive but no thread_limit clause we
6100 // use the default value 0.
6101 return CGF.Builder.getInt32(0);
6102 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006103 }
6104
6105 // No teams associated with the directive.
6106 return nullptr;
6107}
6108
Samuel Antao86ace552016-04-27 22:40:57 +00006109namespace {
6110// \brief Utility to handle information from clauses associated with a given
6111// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6112// It provides a convenient interface to obtain the information and generate
6113// code for that information.
6114class MappableExprsHandler {
6115public:
6116 /// \brief Values for bit flags used to specify the mapping type for
6117 /// offloading.
6118 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006119 /// \brief Allocate memory on the device and move data from host to device.
6120 OMP_MAP_TO = 0x01,
6121 /// \brief Allocate memory on the device and move data from device to host.
6122 OMP_MAP_FROM = 0x02,
6123 /// \brief Always perform the requested mapping action on the element, even
6124 /// if it was already mapped before.
6125 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006126 /// \brief Delete the element from the device environment, ignoring the
6127 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006128 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006129 /// \brief The element being mapped is a pointer-pointee pair; both the
6130 /// pointer and the pointee should be mapped.
6131 OMP_MAP_PTR_AND_OBJ = 0x10,
6132 /// \brief This flags signals that the base address of an entry should be
6133 /// passed to the target kernel as an argument.
6134 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006135 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006136 /// in the current position for the data being mapped. Used when we have the
6137 /// use_device_ptr clause.
6138 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006139 /// \brief This flag signals that the reference being passed is a pointer to
6140 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006141 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006142 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006143 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006144 /// Implicit map
6145 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006146 };
6147
Samuel Antaocc10b852016-07-28 14:23:26 +00006148 /// Class that associates information with a base pointer to be passed to the
6149 /// runtime library.
6150 class BasePointerInfo {
6151 /// The base pointer.
6152 llvm::Value *Ptr = nullptr;
6153 /// The base declaration that refers to this device pointer, or null if
6154 /// there is none.
6155 const ValueDecl *DevPtrDecl = nullptr;
6156
6157 public:
6158 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6159 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6160 llvm::Value *operator*() const { return Ptr; }
6161 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6162 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6163 };
6164
6165 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006166 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006167 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006168
6169private:
6170 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006171 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006172
6173 /// \brief Function the directive is being generated for.
6174 CodeGenFunction &CGF;
6175
Samuel Antaod486f842016-05-26 16:53:38 +00006176 /// \brief Set of all first private variables in the current directive.
6177 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006178 /// Set of all reduction variables in the current directive.
6179 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006180
Samuel Antao6890b092016-07-28 14:25:09 +00006181 /// Map between device pointer declarations and their expression components.
6182 /// The key value for declarations in 'this' is null.
6183 llvm::DenseMap<
6184 const ValueDecl *,
6185 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6186 DevPointersMap;
6187
Samuel Antao86ace552016-04-27 22:40:57 +00006188 llvm::Value *getExprTypeSize(const Expr *E) const {
6189 auto ExprTy = E->getType().getCanonicalType();
6190
6191 // Reference types are ignored for mapping purposes.
6192 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6193 ExprTy = RefTy->getPointeeType().getCanonicalType();
6194
6195 // Given that an array section is considered a built-in type, we need to
6196 // do the calculation based on the length of the section instead of relying
6197 // on CGF.getTypeSize(E->getType()).
6198 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6199 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6200 OAE->getBase()->IgnoreParenImpCasts())
6201 .getCanonicalType();
6202
6203 // If there is no length associated with the expression, that means we
6204 // are using the whole length of the base.
6205 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6206 return CGF.getTypeSize(BaseTy);
6207
6208 llvm::Value *ElemSize;
6209 if (auto *PTy = BaseTy->getAs<PointerType>())
6210 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6211 else {
6212 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6213 assert(ATy && "Expecting array type if not a pointer type.");
6214 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6215 }
6216
6217 // If we don't have a length at this point, that is because we have an
6218 // array section with a single element.
6219 if (!OAE->getLength())
6220 return ElemSize;
6221
6222 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6223 LengthVal =
6224 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6225 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6226 }
6227 return CGF.getTypeSize(ExprTy);
6228 }
6229
6230 /// \brief Return the corresponding bits for a given map clause modifier. Add
6231 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006232 /// map as the first one of a series of maps that relate to the same map
6233 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006234 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006235 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006236 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006237 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006238 switch (MapType) {
6239 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006240 case OMPC_MAP_release:
6241 // alloc and release is the default behavior in the runtime library, i.e.
6242 // if we don't pass any bits alloc/release that is what the runtime is
6243 // going to do. Therefore, we don't need to signal anything for these two
6244 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006245 break;
6246 case OMPC_MAP_to:
6247 Bits = OMP_MAP_TO;
6248 break;
6249 case OMPC_MAP_from:
6250 Bits = OMP_MAP_FROM;
6251 break;
6252 case OMPC_MAP_tofrom:
6253 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6254 break;
6255 case OMPC_MAP_delete:
6256 Bits = OMP_MAP_DELETE;
6257 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006258 default:
6259 llvm_unreachable("Unexpected map type!");
6260 break;
6261 }
6262 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006263 Bits |= OMP_MAP_PTR_AND_OBJ;
6264 if (AddIsTargetParamFlag)
6265 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006266 if (MapTypeModifier == OMPC_MAP_always)
6267 Bits |= OMP_MAP_ALWAYS;
6268 return Bits;
6269 }
6270
6271 /// \brief Return true if the provided expression is a final array section. A
6272 /// final array section, is one whose length can't be proved to be one.
6273 bool isFinalArraySectionExpression(const Expr *E) const {
6274 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6275
6276 // It is not an array section and therefore not a unity-size one.
6277 if (!OASE)
6278 return false;
6279
6280 // An array section with no colon always refer to a single element.
6281 if (OASE->getColonLoc().isInvalid())
6282 return false;
6283
6284 auto *Length = OASE->getLength();
6285
6286 // If we don't have a length we have to check if the array has size 1
6287 // for this dimension. Also, we should always expect a length if the
6288 // base type is pointer.
6289 if (!Length) {
6290 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6291 OASE->getBase()->IgnoreParenImpCasts())
6292 .getCanonicalType();
6293 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6294 return ATy->getSize().getSExtValue() != 1;
6295 // If we don't have a constant dimension length, we have to consider
6296 // the current section as having any size, so it is not necessarily
6297 // unitary. If it happen to be unity size, that's user fault.
6298 return true;
6299 }
6300
6301 // Check if the length evaluates to 1.
6302 llvm::APSInt ConstLength;
6303 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6304 return true; // Can have more that size 1.
6305
6306 return ConstLength.getSExtValue() != 1;
6307 }
6308
6309 /// \brief Generate the base pointers, section pointers, sizes and map type
6310 /// bits for the provided map type, map modifier, and expression components.
6311 /// \a IsFirstComponent should be set to true if the provided set of
6312 /// components is the first associated with a capture.
6313 void generateInfoForComponentList(
6314 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6315 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006316 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006317 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006318 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006319
6320 // The following summarizes what has to be generated for each map and the
6321 // types bellow. The generated information is expressed in this order:
6322 // base pointer, section pointer, size, flags
6323 // (to add to the ones that come from the map type and modifier).
6324 //
6325 // double d;
6326 // int i[100];
6327 // float *p;
6328 //
6329 // struct S1 {
6330 // int i;
6331 // float f[50];
6332 // }
6333 // struct S2 {
6334 // int i;
6335 // float f[50];
6336 // S1 s;
6337 // double *p;
6338 // struct S2 *ps;
6339 // }
6340 // S2 s;
6341 // S2 *ps;
6342 //
6343 // map(d)
6344 // &d, &d, sizeof(double), noflags
6345 //
6346 // map(i)
6347 // &i, &i, 100*sizeof(int), noflags
6348 //
6349 // map(i[1:23])
6350 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6351 //
6352 // map(p)
6353 // &p, &p, sizeof(float*), noflags
6354 //
6355 // map(p[1:24])
6356 // p, &p[1], 24*sizeof(float), noflags
6357 //
6358 // map(s)
6359 // &s, &s, sizeof(S2), noflags
6360 //
6361 // map(s.i)
6362 // &s, &(s.i), sizeof(int), noflags
6363 //
6364 // map(s.s.f)
6365 // &s, &(s.i.f), 50*sizeof(int), noflags
6366 //
6367 // map(s.p)
6368 // &s, &(s.p), sizeof(double*), noflags
6369 //
6370 // map(s.p[:22], s.a s.b)
6371 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006372 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006373 //
6374 // map(s.ps)
6375 // &s, &(s.ps), sizeof(S2*), noflags
6376 //
6377 // map(s.ps->s.i)
6378 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006379 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006380 //
6381 // map(s.ps->ps)
6382 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006383 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006384 //
6385 // map(s.ps->ps->ps)
6386 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006387 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6388 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006389 //
6390 // map(s.ps->ps->s.f[:22])
6391 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006392 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6393 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006394 //
6395 // map(ps)
6396 // &ps, &ps, sizeof(S2*), noflags
6397 //
6398 // map(ps->i)
6399 // ps, &(ps->i), sizeof(int), noflags
6400 //
6401 // map(ps->s.f)
6402 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6403 //
6404 // map(ps->p)
6405 // ps, &(ps->p), sizeof(double*), noflags
6406 //
6407 // map(ps->p[:22])
6408 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006409 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006410 //
6411 // map(ps->ps)
6412 // ps, &(ps->ps), sizeof(S2*), noflags
6413 //
6414 // map(ps->ps->s.i)
6415 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006416 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006417 //
6418 // map(ps->ps->ps)
6419 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006420 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006421 //
6422 // map(ps->ps->ps->ps)
6423 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006424 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6425 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006426 //
6427 // map(ps->ps->ps->s.f[:22])
6428 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006429 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6430 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006431
6432 // Track if the map information being generated is the first for a capture.
6433 bool IsCaptureFirstInfo = IsFirstComponentList;
6434
6435 // Scan the components from the base to the complete expression.
6436 auto CI = Components.rbegin();
6437 auto CE = Components.rend();
6438 auto I = CI;
6439
6440 // Track if the map information being generated is the first for a list of
6441 // components.
6442 bool IsExpressionFirstInfo = true;
6443 llvm::Value *BP = nullptr;
6444
6445 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6446 // The base is the 'this' pointer. The content of the pointer is going
6447 // to be the base of the field being mapped.
6448 BP = CGF.EmitScalarExpr(ME->getBase());
6449 } else {
6450 // The base is the reference to the variable.
6451 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006452 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006453
6454 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006455 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006456 // reference. References are ignored for mapping purposes.
6457 QualType Ty =
6458 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6459 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6460 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006461 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006462 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006463 .getPointer();
6464
6465 // We do not need to generate individual map information for the
6466 // pointer, it can be associated with the combined storage.
6467 ++I;
6468 }
6469 }
6470
George Rokos63bc9d62017-11-21 18:25:12 +00006471 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006472 for (; I != CE; ++I) {
6473 auto Next = std::next(I);
6474
6475 // We need to generate the addresses and sizes if this is the last
6476 // component, if the component is a pointer or if it is an array section
6477 // whose length can't be proved to be one. If this is a pointer, it
6478 // becomes the base address for the following components.
6479
6480 // A final array section, is one whose length can't be proved to be one.
6481 bool IsFinalArraySection =
6482 isFinalArraySectionExpression(I->getAssociatedExpression());
6483
6484 // Get information on whether the element is a pointer. Have to do a
6485 // special treatment for array sections given that they are built-in
6486 // types.
6487 const auto *OASE =
6488 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6489 bool IsPointer =
6490 (OASE &&
6491 OMPArraySectionExpr::getBaseOriginalType(OASE)
6492 .getCanonicalType()
6493 ->isAnyPointerType()) ||
6494 I->getAssociatedExpression()->getType()->isAnyPointerType();
6495
6496 if (Next == CE || IsPointer || IsFinalArraySection) {
6497
6498 // If this is not the last component, we expect the pointer to be
6499 // associated with an array expression or member expression.
6500 assert((Next == CE ||
6501 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6502 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6503 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6504 "Unexpected expression");
6505
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006506 llvm::Value *LB =
6507 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006508 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6509
Samuel Antao03a3cec2016-07-27 22:52:16 +00006510 // If we have a member expression and the current component is a
6511 // reference, we have to map the reference too. Whenever we have a
6512 // reference, the section that reference refers to is going to be a
6513 // load instruction from the storage assigned to the reference.
6514 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6515 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6516 auto *LI = cast<llvm::LoadInst>(LB);
6517 auto *RefAddr = LI->getPointerOperand();
6518
6519 BasePointers.push_back(BP);
6520 Pointers.push_back(RefAddr);
6521 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006522 Types.push_back(DefaultFlags |
6523 getMapTypeBits(
6524 /*MapType*/ OMPC_MAP_alloc,
6525 /*MapTypeModifier=*/OMPC_MAP_unknown,
6526 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006527 IsExpressionFirstInfo = false;
6528 IsCaptureFirstInfo = false;
6529 // The reference will be the next base address.
6530 BP = RefAddr;
6531 }
6532
6533 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006534 Pointers.push_back(LB);
6535 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006536
Samuel Antao6782e942016-05-26 16:48:10 +00006537 // We need to add a pointer flag for each map that comes from the
6538 // same expression except for the first one. We also need to signal
6539 // this map is the first one that relates with the current capture
6540 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006541 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6542 !IsExpressionFirstInfo,
6543 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006544
6545 // If we have a final array section, we are done with this expression.
6546 if (IsFinalArraySection)
6547 break;
6548
6549 // The pointer becomes the base for the next element.
6550 if (Next != CE)
6551 BP = LB;
6552
6553 IsExpressionFirstInfo = false;
6554 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006555 }
6556 }
6557 }
6558
Samuel Antaod486f842016-05-26 16:53:38 +00006559 /// \brief Return the adjusted map modifiers if the declaration a capture
6560 /// refers to appears in a first-private clause. This is expected to be used
6561 /// only with directives that start with 'target'.
6562 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6563 unsigned CurrentModifiers) {
6564 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6565
6566 // A first private variable captured by reference will use only the
6567 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6568 // declaration is known as first-private in this handler.
6569 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
George Rokos065755d2017-11-07 18:27:04 +00006570 return MappableExprsHandler::OMP_MAP_PRIVATE |
Samuel Antaod486f842016-05-26 16:53:38 +00006571 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006572 // Reduction variable will use only the 'private ptr' and 'map to_from'
6573 // flag.
6574 if (ReductionDecls.count(Cap.getCapturedVar())) {
6575 return MappableExprsHandler::OMP_MAP_TO |
6576 MappableExprsHandler::OMP_MAP_FROM;
6577 }
Samuel Antaod486f842016-05-26 16:53:38 +00006578
6579 // We didn't modify anything.
6580 return CurrentModifiers;
6581 }
6582
Samuel Antao86ace552016-04-27 22:40:57 +00006583public:
6584 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006585 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006586 // Extract firstprivate clause information.
6587 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6588 for (const auto *D : C->varlists())
6589 FirstPrivateDecls.insert(
6590 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006591 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
6592 for (const auto *D : C->varlists()) {
6593 ReductionDecls.insert(
6594 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6595 }
6596 }
Samuel Antao6890b092016-07-28 14:25:09 +00006597 // Extract device pointer clause information.
6598 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6599 for (auto L : C->component_lists())
6600 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006601 }
Samuel Antao86ace552016-04-27 22:40:57 +00006602
6603 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006604 /// types for the extracted mappable expressions. Also, for each item that
6605 /// relates with a device pointer, a pair of the relevant declaration and
6606 /// index where it occurs is appended to the device pointers info array.
6607 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006608 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6609 MapFlagsArrayTy &Types) const {
6610 BasePointers.clear();
6611 Pointers.clear();
6612 Sizes.clear();
6613 Types.clear();
6614
6615 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006616 /// Kind that defines how a device pointer has to be returned.
6617 enum ReturnPointerKind {
6618 // Don't have to return any pointer.
6619 RPK_None,
6620 // Pointer is the base of the declaration.
6621 RPK_Base,
6622 // Pointer is a member of the base declaration - 'this'
6623 RPK_Member,
6624 // Pointer is a reference and a member of the base declaration - 'this'
6625 RPK_MemberReference,
6626 };
Samuel Antao86ace552016-04-27 22:40:57 +00006627 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006628 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6629 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6630 ReturnPointerKind ReturnDevicePointer = RPK_None;
6631 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006632
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006633 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006634 MapInfo(
6635 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6636 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006637 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006638 : Components(Components), MapType(MapType),
6639 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006640 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006641 };
6642
6643 // We have to process the component lists that relate with the same
6644 // declaration in a single chunk so that we can generate the map flags
6645 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006646 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006647
6648 // Helper function to fill the information map for the different supported
6649 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006650 auto &&InfoGen = [&Info](
6651 const ValueDecl *D,
6652 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6653 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006654 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006655 const ValueDecl *VD =
6656 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006657 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6658 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006659 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006660
Paul Robinson78fb1322016-08-01 22:12:46 +00006661 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006662 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006663 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006664 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006665 MapInfo::RPK_None, C->isImplicit());
6666 }
Paul Robinson15c84002016-07-29 20:46:16 +00006667 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006668 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006669 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006670 MapInfo::RPK_None, C->isImplicit());
6671 }
Paul Robinson15c84002016-07-29 20:46:16 +00006672 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006673 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006674 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006675 MapInfo::RPK_None, C->isImplicit());
6676 }
Samuel Antao86ace552016-04-27 22:40:57 +00006677
Samuel Antaocc10b852016-07-28 14:23:26 +00006678 // Look at the use_device_ptr clause information and mark the existing map
6679 // entries as such. If there is no map information for an entry in the
6680 // use_device_ptr list, we create one with map type 'alloc' and zero size
6681 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006682 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006683 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006684 for (auto L : C->component_lists()) {
6685 assert(!L.second.empty() && "Not expecting empty list of components!");
6686 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6687 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6688 auto *IE = L.second.back().getAssociatedExpression();
6689 // If the first component is a member expression, we have to look into
6690 // 'this', which maps to null in the map of map information. Otherwise
6691 // look directly for the information.
6692 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6693
6694 // We potentially have map information for this declaration already.
6695 // Look for the first set of components that refer to it.
6696 if (It != Info.end()) {
6697 auto CI = std::find_if(
6698 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6699 return MI.Components.back().getAssociatedDeclaration() == VD;
6700 });
6701 // If we found a map entry, signal that the pointer has to be returned
6702 // and move on to the next declaration.
6703 if (CI != It->second.end()) {
6704 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6705 ? (VD->getType()->isReferenceType()
6706 ? MapInfo::RPK_MemberReference
6707 : MapInfo::RPK_Member)
6708 : MapInfo::RPK_Base;
6709 continue;
6710 }
6711 }
6712
6713 // We didn't find any match in our map information - generate a zero
6714 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006715 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00006716 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
6717 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00006718 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
George Burgess IV00f70bd2018-03-01 05:43:23 +00006789 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00006790
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,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007039 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007040 if (!CGF.HaveInsertPoint())
7041 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007042
Samuel Antaoee8fb302016-01-06 13:42:12 +00007043 assert(OutlinedFn && "Invalid outlined function!");
7044
Alexey Bataev8451efa2018-01-15 19:06:12 +00007045 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7046 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007047 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007048 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7049 PrePostActionTy &) {
7050 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7051 };
7052 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007053
Alexey Bataev8451efa2018-01-15 19:06:12 +00007054 CodeGenFunction::OMPTargetDataInfo InputInfo;
7055 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007056 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007057 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7058 &MapTypesArray, &CS, RequiresOuterTask,
7059 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007060 // On top of the arrays that were filled up, the target offloading call
7061 // takes as arguments the device id as well as the host pointer. The host
7062 // pointer is used by the runtime library to identify the current target
7063 // region, so it only has to be unique and not necessarily point to
7064 // anything. It could be the pointer to the outlined function that
7065 // implements the target region, but we aren't using that so that the
7066 // compiler doesn't need to keep that, and could therefore inline the host
7067 // function if proven worthwhile during optimization.
7068
Samuel Antaoee8fb302016-01-06 13:42:12 +00007069 // From this point on, we need to have an ID of the target region defined.
7070 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007071
7072 // Emit device ID if any.
7073 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007074 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007075 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007076 CGF.Int64Ty, /*isSigned=*/true);
7077 } else {
7078 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7079 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007080
Samuel Antaodf158d52016-04-27 22:58:19 +00007081 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007082 llvm::Value *PointerNum =
7083 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007084
Samuel Antaob68e2db2016-03-03 16:20:23 +00007085 // Return value of the runtime offloading call.
7086 llvm::Value *Return;
7087
Alexey Bataev8451efa2018-01-15 19:06:12 +00007088 auto *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7089 auto *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007090
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007091 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007092 // The target region is an outlined function launched by the runtime
7093 // via calls __tgt_target() or __tgt_target_teams().
7094 //
7095 // __tgt_target() launches a target region with one team and one thread,
7096 // executing a serial region. This master thread may in turn launch
7097 // more threads within its team upon encountering a parallel region,
7098 // however, no additional teams can be launched on the device.
7099 //
7100 // __tgt_target_teams() launches a target region with one or more teams,
7101 // each with one or more threads. This call is required for target
7102 // constructs such as:
7103 // 'target teams'
7104 // 'target' / 'teams'
7105 // 'target teams distribute parallel for'
7106 // 'target parallel'
7107 // and so on.
7108 //
7109 // Note that on the host and CPU targets, the runtime implementation of
7110 // these calls simply call the outlined function without forking threads.
7111 // The outlined functions themselves have runtime calls to
7112 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7113 // the compiler in emitTeamsCall() and emitParallelCall().
7114 //
7115 // In contrast, on the NVPTX target, the implementation of
7116 // __tgt_target_teams() launches a GPU kernel with the requested number
7117 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007118 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007119 // If we have NumTeams defined this means that we have an enclosed teams
7120 // region. Therefore we also expect to have NumThreads defined. These two
7121 // values should be defined in the presence of a teams directive,
7122 // regardless of having any clauses associated. If the user is using teams
7123 // but no clauses, these two values will be the default that should be
7124 // passed to the runtime library - a 32-bit integer with the value zero.
7125 assert(NumThreads && "Thread limit expression should be available along "
7126 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007127 llvm::Value *OffloadingArgs[] = {DeviceID,
7128 OutlinedFnID,
7129 PointerNum,
7130 InputInfo.BasePointersArray.getPointer(),
7131 InputInfo.PointersArray.getPointer(),
7132 InputInfo.SizesArray.getPointer(),
7133 MapTypesArray,
7134 NumTeams,
7135 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007136 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007137 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7138 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007139 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007140 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007141 llvm::Value *OffloadingArgs[] = {DeviceID,
7142 OutlinedFnID,
7143 PointerNum,
7144 InputInfo.BasePointersArray.getPointer(),
7145 InputInfo.PointersArray.getPointer(),
7146 InputInfo.SizesArray.getPointer(),
7147 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007148 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007149 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7150 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007151 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007152 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007153
Alexey Bataev2a007e02017-10-02 14:20:58 +00007154 // Check the error code and execute the host version if required.
7155 llvm::BasicBlock *OffloadFailedBlock =
7156 CGF.createBasicBlock("omp_offload.failed");
7157 llvm::BasicBlock *OffloadContBlock =
7158 CGF.createBasicBlock("omp_offload.cont");
7159 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7160 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7161
7162 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007163 if (RequiresOuterTask) {
7164 CapturedVars.clear();
7165 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7166 }
7167 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007168 CGF.EmitBranch(OffloadContBlock);
7169
7170 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007171 };
7172
Samuel Antaoee8fb302016-01-06 13:42:12 +00007173 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007174 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7175 RequiresOuterTask](CodeGenFunction &CGF,
7176 PrePostActionTy &) {
7177 if (RequiresOuterTask) {
7178 CapturedVars.clear();
7179 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7180 }
7181 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7182 };
7183
7184 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7185 &CapturedVars, RequiresOuterTask,
7186 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7187 // Fill up the arrays with all the captured variables.
7188 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7189 MappableExprsHandler::MapValuesArrayTy Pointers;
7190 MappableExprsHandler::MapValuesArrayTy Sizes;
7191 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7192
7193 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7194 MappableExprsHandler::MapValuesArrayTy CurPointers;
7195 MappableExprsHandler::MapValuesArrayTy CurSizes;
7196 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7197
7198 // Get mappable expression information.
7199 MappableExprsHandler MEHandler(D, CGF);
7200
7201 auto RI = CS.getCapturedRecordDecl()->field_begin();
7202 auto CV = CapturedVars.begin();
7203 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7204 CE = CS.capture_end();
7205 CI != CE; ++CI, ++RI, ++CV) {
7206 CurBasePointers.clear();
7207 CurPointers.clear();
7208 CurSizes.clear();
7209 CurMapTypes.clear();
7210
7211 // VLA sizes are passed to the outlined region by copy and do not have map
7212 // information associated.
7213 if (CI->capturesVariableArrayType()) {
7214 CurBasePointers.push_back(*CV);
7215 CurPointers.push_back(*CV);
7216 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7217 // Copy to the device as an argument. No need to retrieve it.
7218 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7219 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7220 } else {
7221 // If we have any information in the map clause, we use it, otherwise we
7222 // just do a default mapping.
7223 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7224 CurSizes, CurMapTypes);
7225 if (CurBasePointers.empty())
7226 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7227 CurPointers, CurSizes, CurMapTypes);
7228 }
7229 // We expect to have at least an element of information for this capture.
7230 assert(!CurBasePointers.empty() &&
7231 "Non-existing map pointer for capture!");
7232 assert(CurBasePointers.size() == CurPointers.size() &&
7233 CurBasePointers.size() == CurSizes.size() &&
7234 CurBasePointers.size() == CurMapTypes.size() &&
7235 "Inconsistent map information sizes!");
7236
7237 // We need to append the results of this capture to what we already have.
7238 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7239 Pointers.append(CurPointers.begin(), CurPointers.end());
7240 Sizes.append(CurSizes.begin(), CurSizes.end());
7241 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7242 }
7243
7244 TargetDataInfo Info;
7245 // Fill up the arrays and create the arguments.
7246 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7247 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7248 Info.PointersArray, Info.SizesArray,
7249 Info.MapTypesArray, Info);
7250 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7251 InputInfo.BasePointersArray =
7252 Address(Info.BasePointersArray, CGM.getPointerAlign());
7253 InputInfo.PointersArray =
7254 Address(Info.PointersArray, CGM.getPointerAlign());
7255 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7256 MapTypesArray = Info.MapTypesArray;
7257 if (RequiresOuterTask)
7258 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7259 else
7260 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7261 };
7262
7263 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7264 CodeGenFunction &CGF, PrePostActionTy &) {
7265 if (RequiresOuterTask) {
7266 CodeGenFunction::OMPTargetDataInfo InputInfo;
7267 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7268 } else {
7269 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7270 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007271 };
7272
7273 // If we have a target function ID it means that we need to support
7274 // offloading, otherwise, just execute on the host. We need to execute on host
7275 // regardless of the conditional in the if clause if, e.g., the user do not
7276 // specify target triples.
7277 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007278 if (IfCond) {
7279 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7280 } else {
7281 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007282 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007283 }
7284 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007285 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007286 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007287 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007288}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007289
7290void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7291 StringRef ParentName) {
7292 if (!S)
7293 return;
7294
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007295 // Codegen OMP target directives that offload compute to the device.
7296 bool requiresDeviceCodegen =
7297 isa<OMPExecutableDirective>(S) &&
7298 isOpenMPTargetExecutionDirective(
7299 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007300
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007301 if (requiresDeviceCodegen) {
7302 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007303 unsigned DeviceID;
7304 unsigned FileID;
7305 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007306 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007307 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007308
7309 // Is this a target region that should not be emitted as an entry point? If
7310 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007311 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7312 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007313 return;
7314
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007315 switch (S->getStmtClass()) {
7316 case Stmt::OMPTargetDirectiveClass:
7317 CodeGenFunction::EmitOMPTargetDeviceFunction(
7318 CGM, ParentName, cast<OMPTargetDirective>(*S));
7319 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007320 case Stmt::OMPTargetParallelDirectiveClass:
7321 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7322 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7323 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007324 case Stmt::OMPTargetTeamsDirectiveClass:
7325 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7326 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7327 break;
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007328 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
7329 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
7330 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(*S));
7331 break;
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007332 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
7333 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
7334 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(*S));
7335 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007336 case Stmt::OMPTargetParallelForDirectiveClass:
7337 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7338 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7339 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007340 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7341 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7342 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7343 break;
Alexey Bataevf8365372017-11-17 17:57:25 +00007344 case Stmt::OMPTargetSimdDirectiveClass:
7345 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7346 CGM, ParentName, cast<OMPTargetSimdDirective>(*S));
7347 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007348 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
7349 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7350 CGM, ParentName,
7351 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
7352 break;
Alexey Bataev647dd842018-01-15 20:59:40 +00007353 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
7354 CodeGenFunction::
7355 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7356 CGM, ParentName,
7357 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
7358 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007359 default:
7360 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7361 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007362 return;
7363 }
7364
7365 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007366 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007367 return;
7368
7369 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007370 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007371 return;
7372 }
7373
7374 // If this is a lambda function, look into its body.
7375 if (auto *L = dyn_cast<LambdaExpr>(S))
7376 S = L->getBody();
7377
7378 // Keep looking for target regions recursively.
7379 for (auto *II : S->children())
7380 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007381}
7382
7383bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7384 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7385
7386 // If emitting code for the host, we do not process FD here. Instead we do
7387 // the normal code generation.
7388 if (!CGM.getLangOpts().OpenMPIsDevice)
7389 return false;
7390
7391 // Try to detect target regions in the function.
7392 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7393
Samuel Antao4b75b872016-12-12 19:26:31 +00007394 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007395 // scanning. Therefore, we signal that this function is completely dealt
7396 // with.
7397 return true;
7398}
7399
7400bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7401 if (!CGM.getLangOpts().OpenMPIsDevice)
7402 return false;
7403
7404 // Check if there are Ctors/Dtors in this declaration and look for target
7405 // regions in it. We use the complete variant to produce the kernel name
7406 // mangling.
7407 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7408 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7409 for (auto *Ctor : RD->ctors()) {
7410 StringRef ParentName =
7411 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7412 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7413 }
7414 auto *Dtor = RD->getDestructor();
7415 if (Dtor) {
7416 StringRef ParentName =
7417 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7418 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7419 }
7420 }
7421
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007422 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007423 // implemented yet). Therefore we signal that GD was processed in this case.
7424 return true;
7425}
7426
7427bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7428 auto *VD = GD.getDecl();
7429 if (isa<FunctionDecl>(VD))
7430 return emitTargetFunctions(GD);
7431
7432 return emitTargetGlobalVariable(GD);
7433}
7434
7435llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7436 // If we have offloading in the current module, we need to emit the entries
7437 // now and register the offloading descriptor.
7438 createOffloadEntriesAndInfoMetadata();
7439
7440 // Create and register the offloading binary descriptors. This is the main
7441 // entity that captures all the information about offloading in the current
7442 // compilation unit.
7443 return createOffloadingBinaryDescriptorRegistration();
7444}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007445
7446void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7447 const OMPExecutableDirective &D,
7448 SourceLocation Loc,
7449 llvm::Value *OutlinedFn,
7450 ArrayRef<llvm::Value *> CapturedVars) {
7451 if (!CGF.HaveInsertPoint())
7452 return;
7453
7454 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7455 CodeGenFunction::RunCleanupsScope Scope(CGF);
7456
7457 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7458 llvm::Value *Args[] = {
7459 RTLoc,
7460 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7461 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7462 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7463 RealArgs.append(std::begin(Args), std::end(Args));
7464 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7465
7466 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7467 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7468}
7469
7470void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007471 const Expr *NumTeams,
7472 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007473 SourceLocation Loc) {
7474 if (!CGF.HaveInsertPoint())
7475 return;
7476
7477 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7478
Carlo Bertollic6872252016-04-04 15:55:02 +00007479 llvm::Value *NumTeamsVal =
7480 (NumTeams)
7481 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7482 CGF.CGM.Int32Ty, /* isSigned = */ true)
7483 : CGF.Builder.getInt32(0);
7484
7485 llvm::Value *ThreadLimitVal =
7486 (ThreadLimit)
7487 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7488 CGF.CGM.Int32Ty, /* isSigned = */ true)
7489 : CGF.Builder.getInt32(0);
7490
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007491 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007492 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7493 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007494 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7495 PushNumTeamsArgs);
7496}
Samuel Antaodf158d52016-04-27 22:58:19 +00007497
Samuel Antaocc10b852016-07-28 14:23:26 +00007498void CGOpenMPRuntime::emitTargetDataCalls(
7499 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7500 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007501 if (!CGF.HaveInsertPoint())
7502 return;
7503
Samuel Antaocc10b852016-07-28 14:23:26 +00007504 // Action used to replace the default codegen action and turn privatization
7505 // off.
7506 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007507
7508 // Generate the code for the opening of the data environment. Capture all the
7509 // arguments of the runtime call by reference because they are used in the
7510 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007511 auto &&BeginThenGen = [this, &D, Device, &Info,
7512 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007513 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007514 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007515 MappableExprsHandler::MapValuesArrayTy Pointers;
7516 MappableExprsHandler::MapValuesArrayTy Sizes;
7517 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7518
7519 // Get map clause information.
7520 MappableExprsHandler MCHandler(D, CGF);
7521 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007522
7523 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007524 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007525
7526 llvm::Value *BasePointersArrayArg = nullptr;
7527 llvm::Value *PointersArrayArg = nullptr;
7528 llvm::Value *SizesArrayArg = nullptr;
7529 llvm::Value *MapTypesArrayArg = nullptr;
7530 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007531 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007532
7533 // Emit device ID if any.
7534 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007535 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007536 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007537 CGF.Int64Ty, /*isSigned=*/true);
7538 } else {
7539 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7540 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007541
7542 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007543 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007544
7545 llvm::Value *OffloadingArgs[] = {
7546 DeviceID, PointerNum, BasePointersArrayArg,
7547 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007548 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00007549 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007550
7551 // If device pointer privatization is required, emit the body of the region
7552 // here. It will have to be duplicated: with and without privatization.
7553 if (!Info.CaptureDeviceAddrMap.empty())
7554 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007555 };
7556
7557 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007558 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
7559 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007560 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007561
7562 llvm::Value *BasePointersArrayArg = nullptr;
7563 llvm::Value *PointersArrayArg = nullptr;
7564 llvm::Value *SizesArrayArg = nullptr;
7565 llvm::Value *MapTypesArrayArg = nullptr;
7566 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007567 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007568
7569 // Emit device ID if any.
7570 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007571 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007572 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007573 CGF.Int64Ty, /*isSigned=*/true);
7574 } else {
7575 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7576 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007577
7578 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007579 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007580
7581 llvm::Value *OffloadingArgs[] = {
7582 DeviceID, PointerNum, BasePointersArrayArg,
7583 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007584 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00007585 OffloadingArgs);
7586 };
7587
Samuel Antaocc10b852016-07-28 14:23:26 +00007588 // If we need device pointer privatization, we need to emit the body of the
7589 // region with no privatization in the 'else' branch of the conditional.
7590 // Otherwise, we don't have to do anything.
7591 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7592 PrePostActionTy &) {
7593 if (!Info.CaptureDeviceAddrMap.empty()) {
7594 CodeGen.setAction(NoPrivAction);
7595 CodeGen(CGF);
7596 }
7597 };
7598
7599 // We don't have to do anything to close the region if the if clause evaluates
7600 // to false.
7601 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007602
7603 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007604 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007605 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007606 RegionCodeGenTy RCG(BeginThenGen);
7607 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007608 }
7609
Samuel Antaocc10b852016-07-28 14:23:26 +00007610 // If we don't require privatization of device pointers, we emit the body in
7611 // between the runtime calls. This avoids duplicating the body code.
7612 if (Info.CaptureDeviceAddrMap.empty()) {
7613 CodeGen.setAction(NoPrivAction);
7614 CodeGen(CGF);
7615 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007616
7617 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007618 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007619 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007620 RegionCodeGenTy RCG(EndThenGen);
7621 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007622 }
7623}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007624
Samuel Antao8d2d7302016-05-26 18:30:22 +00007625void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007626 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7627 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007628 if (!CGF.HaveInsertPoint())
7629 return;
7630
Samuel Antao8dd66282016-04-27 23:14:30 +00007631 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007632 isa<OMPTargetExitDataDirective>(D) ||
7633 isa<OMPTargetUpdateDirective>(D)) &&
7634 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007635
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007636 CodeGenFunction::OMPTargetDataInfo InputInfo;
7637 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007638 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007639 auto &&ThenGen = [this, &D, Device, &InputInfo,
7640 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007641 // Emit device ID if any.
7642 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007643 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007644 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007645 CGF.Int64Ty, /*isSigned=*/true);
7646 } else {
7647 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7648 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007649
7650 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007651 llvm::Constant *PointerNum =
7652 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007653
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007654 llvm::Value *OffloadingArgs[] = {DeviceID,
7655 PointerNum,
7656 InputInfo.BasePointersArray.getPointer(),
7657 InputInfo.PointersArray.getPointer(),
7658 InputInfo.SizesArray.getPointer(),
7659 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007660
Samuel Antao8d2d7302016-05-26 18:30:22 +00007661 // Select the right runtime function call for each expected standalone
7662 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007663 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007664 OpenMPRTLFunction RTLFn;
7665 switch (D.getDirectiveKind()) {
7666 default:
7667 llvm_unreachable("Unexpected standalone target data directive.");
7668 break;
7669 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007670 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
7671 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007672 break;
7673 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007674 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
7675 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007676 break;
7677 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007678 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
7679 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007680 break;
7681 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007682 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007683 };
7684
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007685 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
7686 CodeGenFunction &CGF, PrePostActionTy &) {
7687 // Fill up the arrays with all the mapped variables.
7688 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7689 MappableExprsHandler::MapValuesArrayTy Pointers;
7690 MappableExprsHandler::MapValuesArrayTy Sizes;
7691 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007692
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007693 // Get map clause information.
7694 MappableExprsHandler MEHandler(D, CGF);
7695 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
7696
7697 TargetDataInfo Info;
7698 // Fill up the arrays and create the arguments.
7699 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7700 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7701 Info.PointersArray, Info.SizesArray,
7702 Info.MapTypesArray, Info);
7703 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7704 InputInfo.BasePointersArray =
7705 Address(Info.BasePointersArray, CGM.getPointerAlign());
7706 InputInfo.PointersArray =
7707 Address(Info.PointersArray, CGM.getPointerAlign());
7708 InputInfo.SizesArray =
7709 Address(Info.SizesArray, CGM.getPointerAlign());
7710 MapTypesArray = Info.MapTypesArray;
7711 if (D.hasClausesOfKind<OMPDependClause>())
7712 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7713 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00007714 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007715 };
7716
7717 if (IfCond)
7718 emitOMPIfClause(CGF, IfCond, TargetThenGen,
7719 [](CodeGenFunction &CGF, PrePostActionTy &) {});
7720 else {
7721 RegionCodeGenTy ThenRCG(TargetThenGen);
7722 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007723 }
7724}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007725
7726namespace {
7727 /// Kind of parameter in a function with 'declare simd' directive.
7728 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7729 /// Attribute set of the parameter.
7730 struct ParamAttrTy {
7731 ParamKindTy Kind = Vector;
7732 llvm::APSInt StrideOrArg;
7733 llvm::APSInt Alignment;
7734 };
7735} // namespace
7736
7737static unsigned evaluateCDTSize(const FunctionDecl *FD,
7738 ArrayRef<ParamAttrTy> ParamAttrs) {
7739 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7740 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7741 // of that clause. The VLEN value must be power of 2.
7742 // In other case the notion of the function`s "characteristic data type" (CDT)
7743 // is used to compute the vector length.
7744 // CDT is defined in the following order:
7745 // a) For non-void function, the CDT is the return type.
7746 // b) If the function has any non-uniform, non-linear parameters, then the
7747 // CDT is the type of the first such parameter.
7748 // c) If the CDT determined by a) or b) above is struct, union, or class
7749 // type which is pass-by-value (except for the type that maps to the
7750 // built-in complex data type), the characteristic data type is int.
7751 // d) If none of the above three cases is applicable, the CDT is int.
7752 // The VLEN is then determined based on the CDT and the size of vector
7753 // register of that ISA for which current vector version is generated. The
7754 // VLEN is computed using the formula below:
7755 // VLEN = sizeof(vector_register) / sizeof(CDT),
7756 // where vector register size specified in section 3.2.1 Registers and the
7757 // Stack Frame of original AMD64 ABI document.
7758 QualType RetType = FD->getReturnType();
7759 if (RetType.isNull())
7760 return 0;
7761 ASTContext &C = FD->getASTContext();
7762 QualType CDT;
7763 if (!RetType.isNull() && !RetType->isVoidType())
7764 CDT = RetType;
7765 else {
7766 unsigned Offset = 0;
7767 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7768 if (ParamAttrs[Offset].Kind == Vector)
7769 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7770 ++Offset;
7771 }
7772 if (CDT.isNull()) {
7773 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7774 if (ParamAttrs[I + Offset].Kind == Vector) {
7775 CDT = FD->getParamDecl(I)->getType();
7776 break;
7777 }
7778 }
7779 }
7780 }
7781 if (CDT.isNull())
7782 CDT = C.IntTy;
7783 CDT = CDT->getCanonicalTypeUnqualified();
7784 if (CDT->isRecordType() || CDT->isUnionType())
7785 CDT = C.IntTy;
7786 return C.getTypeSize(CDT);
7787}
7788
7789static void
7790emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007791 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007792 ArrayRef<ParamAttrTy> ParamAttrs,
7793 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7794 struct ISADataTy {
7795 char ISA;
7796 unsigned VecRegSize;
7797 };
7798 ISADataTy ISAData[] = {
7799 {
7800 'b', 128
7801 }, // SSE
7802 {
7803 'c', 256
7804 }, // AVX
7805 {
7806 'd', 256
7807 }, // AVX2
7808 {
7809 'e', 512
7810 }, // AVX512
7811 };
7812 llvm::SmallVector<char, 2> Masked;
7813 switch (State) {
7814 case OMPDeclareSimdDeclAttr::BS_Undefined:
7815 Masked.push_back('N');
7816 Masked.push_back('M');
7817 break;
7818 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7819 Masked.push_back('N');
7820 break;
7821 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7822 Masked.push_back('M');
7823 break;
7824 }
7825 for (auto Mask : Masked) {
7826 for (auto &Data : ISAData) {
7827 SmallString<256> Buffer;
7828 llvm::raw_svector_ostream Out(Buffer);
7829 Out << "_ZGV" << Data.ISA << Mask;
7830 if (!VLENVal) {
7831 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7832 evaluateCDTSize(FD, ParamAttrs));
7833 } else
7834 Out << VLENVal;
7835 for (auto &ParamAttr : ParamAttrs) {
7836 switch (ParamAttr.Kind){
7837 case LinearWithVarStride:
7838 Out << 's' << ParamAttr.StrideOrArg;
7839 break;
7840 case Linear:
7841 Out << 'l';
7842 if (!!ParamAttr.StrideOrArg)
7843 Out << ParamAttr.StrideOrArg;
7844 break;
7845 case Uniform:
7846 Out << 'u';
7847 break;
7848 case Vector:
7849 Out << 'v';
7850 break;
7851 }
7852 if (!!ParamAttr.Alignment)
7853 Out << 'a' << ParamAttr.Alignment;
7854 }
7855 Out << '_' << Fn->getName();
7856 Fn->addFnAttr(Out.str());
7857 }
7858 }
7859}
7860
7861void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7862 llvm::Function *Fn) {
7863 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007864 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007865 // Map params to their positions in function decl.
7866 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7867 if (isa<CXXMethodDecl>(FD))
7868 ParamPositions.insert({FD, 0});
7869 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007870 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007871 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7872 ++ParamPos;
7873 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007874 while (FD) {
7875 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7876 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7877 // Mark uniform parameters.
7878 for (auto *E : Attr->uniforms()) {
7879 E = E->IgnoreParenImpCasts();
7880 unsigned Pos;
7881 if (isa<CXXThisExpr>(E))
7882 Pos = ParamPositions[FD];
7883 else {
7884 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7885 ->getCanonicalDecl();
7886 Pos = ParamPositions[PVD];
7887 }
7888 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007889 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007890 // Get alignment info.
7891 auto NI = Attr->alignments_begin();
7892 for (auto *E : Attr->aligneds()) {
7893 E = E->IgnoreParenImpCasts();
7894 unsigned Pos;
7895 QualType ParmTy;
7896 if (isa<CXXThisExpr>(E)) {
7897 Pos = ParamPositions[FD];
7898 ParmTy = E->getType();
7899 } else {
7900 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7901 ->getCanonicalDecl();
7902 Pos = ParamPositions[PVD];
7903 ParmTy = PVD->getType();
7904 }
7905 ParamAttrs[Pos].Alignment =
7906 (*NI)
7907 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007908 : llvm::APSInt::getUnsigned(
7909 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7910 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007911 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007912 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007913 // Mark linear parameters.
7914 auto SI = Attr->steps_begin();
7915 auto MI = Attr->modifiers_begin();
7916 for (auto *E : Attr->linears()) {
7917 E = E->IgnoreParenImpCasts();
7918 unsigned Pos;
7919 if (isa<CXXThisExpr>(E))
7920 Pos = ParamPositions[FD];
7921 else {
7922 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7923 ->getCanonicalDecl();
7924 Pos = ParamPositions[PVD];
7925 }
7926 auto &ParamAttr = ParamAttrs[Pos];
7927 ParamAttr.Kind = Linear;
7928 if (*SI) {
7929 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7930 Expr::SE_AllowSideEffects)) {
7931 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7932 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7933 ParamAttr.Kind = LinearWithVarStride;
7934 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7935 ParamPositions[StridePVD->getCanonicalDecl()]);
7936 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007937 }
7938 }
7939 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007940 ++SI;
7941 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007942 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007943 llvm::APSInt VLENVal;
7944 if (const Expr *VLEN = Attr->getSimdlen())
7945 VLENVal = VLEN->EvaluateKnownConstInt(C);
7946 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7947 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7948 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7949 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007950 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007951 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007952 }
7953}
Alexey Bataev8b427062016-05-25 12:36:08 +00007954
7955namespace {
7956/// Cleanup action for doacross support.
7957class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7958public:
7959 static const int DoacrossFinArgs = 2;
7960
7961private:
7962 llvm::Value *RTLFn;
7963 llvm::Value *Args[DoacrossFinArgs];
7964
7965public:
7966 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7967 : RTLFn(RTLFn) {
7968 assert(CallArgs.size() == DoacrossFinArgs);
7969 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7970 }
7971 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7972 if (!CGF.HaveInsertPoint())
7973 return;
7974 CGF.EmitRuntimeCall(RTLFn, Args);
7975 }
7976};
7977} // namespace
7978
7979void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7980 const OMPLoopDirective &D) {
7981 if (!CGF.HaveInsertPoint())
7982 return;
7983
7984 ASTContext &C = CGM.getContext();
7985 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7986 RecordDecl *RD;
7987 if (KmpDimTy.isNull()) {
7988 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7989 // kmp_int64 lo; // lower
7990 // kmp_int64 up; // upper
7991 // kmp_int64 st; // stride
7992 // };
7993 RD = C.buildImplicitRecord("kmp_dim");
7994 RD->startDefinition();
7995 addFieldToRecordDecl(C, RD, Int64Ty);
7996 addFieldToRecordDecl(C, RD, Int64Ty);
7997 addFieldToRecordDecl(C, RD, Int64Ty);
7998 RD->completeDefinition();
7999 KmpDimTy = C.getRecordType(RD);
8000 } else
8001 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
8002
8003 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8004 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8005 enum { LowerFD = 0, UpperFD, StrideFD };
8006 // Fill dims with data.
8007 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8008 // dims.upper = num_iterations;
8009 LValue UpperLVal =
8010 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8011 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8012 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8013 Int64Ty, D.getNumIterations()->getExprLoc());
8014 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8015 // dims.stride = 1;
8016 LValue StrideLVal =
8017 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8018 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8019 StrideLVal);
8020
8021 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8022 // kmp_int32 num_dims, struct kmp_dim * dims);
8023 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8024 getThreadID(CGF, D.getLocStart()),
8025 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8026 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8027 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8028
8029 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8030 CGF.EmitRuntimeCall(RTLFn, Args);
8031 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8032 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8033 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8034 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8035 llvm::makeArrayRef(FiniArgs));
8036}
8037
8038void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8039 const OMPDependClause *C) {
8040 QualType Int64Ty =
8041 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8042 const Expr *CounterVal = C->getCounterValue();
8043 assert(CounterVal);
8044 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8045 CounterVal->getType(), Int64Ty,
8046 CounterVal->getExprLoc());
8047 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8048 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8049 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8050 getThreadID(CGF, C->getLocStart()),
8051 CntAddr.getPointer()};
8052 llvm::Value *RTLFn;
8053 if (C->getDependencyKind() == OMPC_DEPEND_source)
8054 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
8055 else {
8056 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8057 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8058 }
8059 CGF.EmitRuntimeCall(RTLFn, Args);
8060}
8061
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008062void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8063 llvm::Value *Callee,
8064 ArrayRef<llvm::Value *> Args) const {
8065 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008066 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8067
8068 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008069 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008070 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008071 return;
8072 }
8073 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008074 CGF.EmitRuntimeCall(Callee, Args);
8075}
8076
8077void CGOpenMPRuntime::emitOutlinedFunctionCall(
8078 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8079 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008080 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008081}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008082
8083Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8084 const VarDecl *NativeParam,
8085 const VarDecl *TargetParam) const {
8086 return CGF.GetAddrOfLocalVar(NativeParam);
8087}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008088
8089llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8090 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8091 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8092 llvm_unreachable("Not supported in SIMD-only mode");
8093}
8094
8095llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8096 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8097 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8098 llvm_unreachable("Not supported in SIMD-only mode");
8099}
8100
8101llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8102 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8103 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8104 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8105 bool Tied, unsigned &NumberOfParts) {
8106 llvm_unreachable("Not supported in SIMD-only mode");
8107}
8108
8109void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8110 SourceLocation Loc,
8111 llvm::Value *OutlinedFn,
8112 ArrayRef<llvm::Value *> CapturedVars,
8113 const Expr *IfCond) {
8114 llvm_unreachable("Not supported in SIMD-only mode");
8115}
8116
8117void CGOpenMPSIMDRuntime::emitCriticalRegion(
8118 CodeGenFunction &CGF, StringRef CriticalName,
8119 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8120 const Expr *Hint) {
8121 llvm_unreachable("Not supported in SIMD-only mode");
8122}
8123
8124void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8125 const RegionCodeGenTy &MasterOpGen,
8126 SourceLocation Loc) {
8127 llvm_unreachable("Not supported in SIMD-only mode");
8128}
8129
8130void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8131 SourceLocation Loc) {
8132 llvm_unreachable("Not supported in SIMD-only mode");
8133}
8134
8135void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8136 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8137 SourceLocation Loc) {
8138 llvm_unreachable("Not supported in SIMD-only mode");
8139}
8140
8141void CGOpenMPSIMDRuntime::emitSingleRegion(
8142 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8143 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8144 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8145 ArrayRef<const Expr *> AssignmentOps) {
8146 llvm_unreachable("Not supported in SIMD-only mode");
8147}
8148
8149void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8150 const RegionCodeGenTy &OrderedOpGen,
8151 SourceLocation Loc,
8152 bool IsThreads) {
8153 llvm_unreachable("Not supported in SIMD-only mode");
8154}
8155
8156void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8157 SourceLocation Loc,
8158 OpenMPDirectiveKind Kind,
8159 bool EmitChecks,
8160 bool ForceSimpleCall) {
8161 llvm_unreachable("Not supported in SIMD-only mode");
8162}
8163
8164void CGOpenMPSIMDRuntime::emitForDispatchInit(
8165 CodeGenFunction &CGF, SourceLocation Loc,
8166 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8167 bool Ordered, const DispatchRTInput &DispatchValues) {
8168 llvm_unreachable("Not supported in SIMD-only mode");
8169}
8170
8171void CGOpenMPSIMDRuntime::emitForStaticInit(
8172 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8173 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8174 llvm_unreachable("Not supported in SIMD-only mode");
8175}
8176
8177void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8178 CodeGenFunction &CGF, SourceLocation Loc,
8179 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8180 llvm_unreachable("Not supported in SIMD-only mode");
8181}
8182
8183void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8184 SourceLocation Loc,
8185 unsigned IVSize,
8186 bool IVSigned) {
8187 llvm_unreachable("Not supported in SIMD-only mode");
8188}
8189
8190void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8191 SourceLocation Loc,
8192 OpenMPDirectiveKind DKind) {
8193 llvm_unreachable("Not supported in SIMD-only mode");
8194}
8195
8196llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8197 SourceLocation Loc,
8198 unsigned IVSize, bool IVSigned,
8199 Address IL, Address LB,
8200 Address UB, Address ST) {
8201 llvm_unreachable("Not supported in SIMD-only mode");
8202}
8203
8204void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8205 llvm::Value *NumThreads,
8206 SourceLocation Loc) {
8207 llvm_unreachable("Not supported in SIMD-only mode");
8208}
8209
8210void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8211 OpenMPProcBindClauseKind ProcBind,
8212 SourceLocation Loc) {
8213 llvm_unreachable("Not supported in SIMD-only mode");
8214}
8215
8216Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8217 const VarDecl *VD,
8218 Address VDAddr,
8219 SourceLocation Loc) {
8220 llvm_unreachable("Not supported in SIMD-only mode");
8221}
8222
8223llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8224 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8225 CodeGenFunction *CGF) {
8226 llvm_unreachable("Not supported in SIMD-only mode");
8227}
8228
8229Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8230 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8231 llvm_unreachable("Not supported in SIMD-only mode");
8232}
8233
8234void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8235 ArrayRef<const Expr *> Vars,
8236 SourceLocation Loc) {
8237 llvm_unreachable("Not supported in SIMD-only mode");
8238}
8239
8240void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8241 const OMPExecutableDirective &D,
8242 llvm::Value *TaskFunction,
8243 QualType SharedsTy, Address Shareds,
8244 const Expr *IfCond,
8245 const OMPTaskDataTy &Data) {
8246 llvm_unreachable("Not supported in SIMD-only mode");
8247}
8248
8249void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8250 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8251 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8252 const Expr *IfCond, const OMPTaskDataTy &Data) {
8253 llvm_unreachable("Not supported in SIMD-only mode");
8254}
8255
8256void CGOpenMPSIMDRuntime::emitReduction(
8257 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8258 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8259 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8260 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8261 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8262 ReductionOps, Options);
8263}
8264
8265llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8266 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8267 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8268 llvm_unreachable("Not supported in SIMD-only mode");
8269}
8270
8271void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8272 SourceLocation Loc,
8273 ReductionCodeGen &RCG,
8274 unsigned N) {
8275 llvm_unreachable("Not supported in SIMD-only mode");
8276}
8277
8278Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8279 SourceLocation Loc,
8280 llvm::Value *ReductionsPtr,
8281 LValue SharedLVal) {
8282 llvm_unreachable("Not supported in SIMD-only mode");
8283}
8284
8285void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8286 SourceLocation Loc) {
8287 llvm_unreachable("Not supported in SIMD-only mode");
8288}
8289
8290void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8291 CodeGenFunction &CGF, SourceLocation Loc,
8292 OpenMPDirectiveKind CancelRegion) {
8293 llvm_unreachable("Not supported in SIMD-only mode");
8294}
8295
8296void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8297 SourceLocation Loc, const Expr *IfCond,
8298 OpenMPDirectiveKind CancelRegion) {
8299 llvm_unreachable("Not supported in SIMD-only mode");
8300}
8301
8302void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8303 const OMPExecutableDirective &D, StringRef ParentName,
8304 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8305 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8306 llvm_unreachable("Not supported in SIMD-only mode");
8307}
8308
8309void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8310 const OMPExecutableDirective &D,
8311 llvm::Value *OutlinedFn,
8312 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008313 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008314 llvm_unreachable("Not supported in SIMD-only mode");
8315}
8316
8317bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8318 llvm_unreachable("Not supported in SIMD-only mode");
8319}
8320
8321bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8322 llvm_unreachable("Not supported in SIMD-only mode");
8323}
8324
8325bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8326 return false;
8327}
8328
8329llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8330 return nullptr;
8331}
8332
8333void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8334 const OMPExecutableDirective &D,
8335 SourceLocation Loc,
8336 llvm::Value *OutlinedFn,
8337 ArrayRef<llvm::Value *> CapturedVars) {
8338 llvm_unreachable("Not supported in SIMD-only mode");
8339}
8340
8341void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8342 const Expr *NumTeams,
8343 const Expr *ThreadLimit,
8344 SourceLocation Loc) {
8345 llvm_unreachable("Not supported in SIMD-only mode");
8346}
8347
8348void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8349 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8350 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8351 llvm_unreachable("Not supported in SIMD-only mode");
8352}
8353
8354void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8355 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8356 const Expr *Device) {
8357 llvm_unreachable("Not supported in SIMD-only mode");
8358}
8359
8360void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8361 const OMPLoopDirective &D) {
8362 llvm_unreachable("Not supported in SIMD-only mode");
8363}
8364
8365void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8366 const OMPDependClause *C) {
8367 llvm_unreachable("Not supported in SIMD-only mode");
8368}
8369
8370const VarDecl *
8371CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8372 const VarDecl *NativeParam) const {
8373 llvm_unreachable("Not supported in SIMD-only mode");
8374}
8375
8376Address
8377CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8378 const VarDecl *NativeParam,
8379 const VarDecl *TargetParam) const {
8380 llvm_unreachable("Not supported in SIMD-only mode");
8381}
8382