blob: 85a9211917a663801fa1eff21de250a516be81b3 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
195 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Alexey Bataev311a9282017-10-12 13:51:32 +0000268 /// \brief Get an LValue for the current ThreadID variable.
269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct");
273 }
274
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000275 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000276 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 llvm_unreachable("No helper name for inlined OpenMP construct");
280 }
281
Alexey Bataev48591dd2016-04-20 04:01:36 +0000282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
Alexey Bataev48591dd2016-04-20 04:01:36 +0000294 ~CGOpenMPInlinedRegionInfo() override = default;
295
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000296private:
297 /// \brief CodeGen info about outer OpenMP region.
298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000300};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000301
Samuel Antaobed3c462015-10-02 16:14:20 +0000302/// \brief API for captured statement code generation in OpenMP target
303/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 /// \brief This is unused for target regions because each starts executing
316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
319 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000320 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000326
327private:
328 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000329};
330
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000332 llvm_unreachable("No codegen for expressions");
333}
334/// \brief API for generation of expressions captured in a innermost OpenMP
335/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
346 for (auto &C : CS.captures()) {
347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
354 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
357 SourceLocation());
358 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
359 return CGF.EmitLValue(&DRE).getAddress();
360 });
361 }
362 (void)PrivScope.Privatize();
363 }
364
365 /// \brief Lookup the captured field decl for a variable.
366 const FieldDecl *lookup(const VarDecl *VD) const override {
367 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
368 return FD;
369 return nullptr;
370 }
371
372 /// \brief Emit the captured statement body.
373 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
374 llvm_unreachable("No body for expressions");
375 }
376
377 /// \brief Get a variable or parameter for storing global thread id
378 /// inside OpenMP construct.
379 const VarDecl *getThreadIDVariable() const override {
380 llvm_unreachable("No thread id for expressions");
381 }
382
383 /// \brief Get the name of the capture helper.
384 StringRef getHelperName() const override {
385 llvm_unreachable("No helper name for expressions");
386 }
387
388 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
389
390private:
391 /// Private scope to capture global variables.
392 CodeGenFunction::OMPPrivateScope PrivScope;
393};
394
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000395/// \brief RAII for emitting code of OpenMP constructs.
396class InlinedOpenMPRegionRAII {
397 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000398 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
399 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400
401public:
402 /// \brief Constructs region for combined constructs.
403 /// \param CodeGen Code generation sequence for combined directives. Includes
404 /// a list of functions used for code generation of implicitly inlined
405 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000406 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000407 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 : CGF(CGF) {
409 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000410 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
411 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
413 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
414 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000415 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000416
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 ~InlinedOpenMPRegionRAII() {
418 // Restore original CapturedStmtInfo only if we're done with code emission.
419 auto *OldCSI =
420 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
421 delete CGF.CapturedStmtInfo;
422 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000423 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
424 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000425 }
426};
427
Alexey Bataev50b3c952016-02-19 10:38:26 +0000428/// \brief Values for bit flags used in the ident_t to describe the fields.
429/// All enumeric elements are named and described in accordance with the code
430/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000431enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432 /// \brief Use trampoline for internal microtask.
433 OMP_IDENT_IMD = 0x01,
434 /// \brief Use c-style ident structure.
435 OMP_IDENT_KMPC = 0x02,
436 /// \brief Atomic reduction option for kmpc_reduce.
437 OMP_ATOMIC_REDUCE = 0x10,
438 /// \brief Explicit 'barrier' directive.
439 OMP_IDENT_BARRIER_EXPL = 0x20,
440 /// \brief Implicit barrier in code.
441 OMP_IDENT_BARRIER_IMPL = 0x40,
442 /// \brief Implicit barrier in 'for' directive.
443 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
444 /// \brief Implicit barrier in 'sections' directive.
445 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
446 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000447 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
448 /// Call of __kmp_for_static_init for static loop.
449 OMP_IDENT_WORK_LOOP = 0x200,
450 /// Call of __kmp_for_static_init for sections.
451 OMP_IDENT_WORK_SECTIONS = 0x400,
452 /// Call of __kmp_for_static_init for distribute.
453 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
454 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000455};
456
457/// \brief Describes ident structure that describes a source location.
458/// All descriptions are taken from
459/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
460/// Original structure:
461/// typedef struct ident {
462/// kmp_int32 reserved_1; /**< might be used in Fortran;
463/// see above */
464/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
465/// KMP_IDENT_KMPC identifies this union
466/// member */
467/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
468/// see above */
469///#if USE_ITT_BUILD
470/// /* but currently used for storing
471/// region-specific ITT */
472/// /* contextual information. */
473///#endif /* USE_ITT_BUILD */
474/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
475/// C++ */
476/// char const *psource; /**< String describing the source location.
477/// The string is composed of semi-colon separated
478// fields which describe the source file,
479/// the function and a pair of line numbers that
480/// delimit the construct.
481/// */
482/// } ident_t;
483enum IdentFieldIndex {
484 /// \brief might be used in Fortran
485 IdentField_Reserved_1,
486 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
487 IdentField_Flags,
488 /// \brief Not really used in Fortran any more
489 IdentField_Reserved_2,
490 /// \brief Source[4] in Fortran, do not use for C++
491 IdentField_Reserved_3,
492 /// \brief String describing the source location. The string is composed of
493 /// semi-colon separated fields which describe the source file, the function
494 /// and a pair of line numbers that delimit the construct.
495 IdentField_PSource
496};
497
498/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
499/// the enum sched_type in kmp.h).
500enum OpenMPSchedType {
501 /// \brief Lower bound for default (unordered) versions.
502 OMP_sch_lower = 32,
503 OMP_sch_static_chunked = 33,
504 OMP_sch_static = 34,
505 OMP_sch_dynamic_chunked = 35,
506 OMP_sch_guided_chunked = 36,
507 OMP_sch_runtime = 37,
508 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000509 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000510 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000511 /// \brief Lower bound for 'ordered' versions.
512 OMP_ord_lower = 64,
513 OMP_ord_static_chunked = 65,
514 OMP_ord_static = 66,
515 OMP_ord_dynamic_chunked = 67,
516 OMP_ord_guided_chunked = 68,
517 OMP_ord_runtime = 69,
518 OMP_ord_auto = 70,
519 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000520 /// \brief dist_schedule types
521 OMP_dist_sch_static_chunked = 91,
522 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000523 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
524 /// Set if the monotonic schedule modifier was present.
525 OMP_sch_modifier_monotonic = (1 << 29),
526 /// Set if the nonmonotonic schedule modifier was present.
527 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000528};
529
530enum OpenMPRTLFunction {
531 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
532 /// kmpc_micro microtask, ...);
533 OMPRTL__kmpc_fork_call,
534 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
535 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
536 OMPRTL__kmpc_threadprivate_cached,
537 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
538 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
539 OMPRTL__kmpc_threadprivate_register,
540 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
541 OMPRTL__kmpc_global_thread_num,
542 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
543 // kmp_critical_name *crit);
544 OMPRTL__kmpc_critical,
545 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
546 // global_tid, kmp_critical_name *crit, uintptr_t hint);
547 OMPRTL__kmpc_critical_with_hint,
548 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
549 // kmp_critical_name *crit);
550 OMPRTL__kmpc_end_critical,
551 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
552 // global_tid);
553 OMPRTL__kmpc_cancel_barrier,
554 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
555 OMPRTL__kmpc_barrier,
556 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
557 OMPRTL__kmpc_for_static_fini,
558 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
559 // global_tid);
560 OMPRTL__kmpc_serialized_parallel,
561 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 OMPRTL__kmpc_end_serialized_parallel,
564 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
565 // kmp_int32 num_threads);
566 OMPRTL__kmpc_push_num_threads,
567 // Call to void __kmpc_flush(ident_t *loc);
568 OMPRTL__kmpc_flush,
569 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
570 OMPRTL__kmpc_master,
571 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
572 OMPRTL__kmpc_end_master,
573 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
574 // int end_part);
575 OMPRTL__kmpc_omp_taskyield,
576 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_single,
578 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
579 OMPRTL__kmpc_end_single,
580 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
581 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
582 // kmp_routine_entry_t *task_entry);
583 OMPRTL__kmpc_omp_task_alloc,
584 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
585 // new_task);
586 OMPRTL__kmpc_omp_task,
587 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
588 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
589 // kmp_int32 didit);
590 OMPRTL__kmpc_copyprivate,
591 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
592 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
593 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
594 OMPRTL__kmpc_reduce,
595 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
596 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
597 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
598 // *lck);
599 OMPRTL__kmpc_reduce_nowait,
600 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
601 // kmp_critical_name *lck);
602 OMPRTL__kmpc_end_reduce,
603 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
604 // kmp_critical_name *lck);
605 OMPRTL__kmpc_end_reduce_nowait,
606 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
607 // kmp_task_t * new_task);
608 OMPRTL__kmpc_omp_task_begin_if0,
609 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
610 // kmp_task_t * new_task);
611 OMPRTL__kmpc_omp_task_complete_if0,
612 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
613 OMPRTL__kmpc_ordered,
614 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
615 OMPRTL__kmpc_end_ordered,
616 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
617 // global_tid);
618 OMPRTL__kmpc_omp_taskwait,
619 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_taskgroup,
621 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
622 OMPRTL__kmpc_end_taskgroup,
623 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
624 // int proc_bind);
625 OMPRTL__kmpc_push_proc_bind,
626 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
627 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
628 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
629 OMPRTL__kmpc_omp_task_with_deps,
630 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
632 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_wait_deps,
634 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
635 // global_tid, kmp_int32 cncl_kind);
636 OMPRTL__kmpc_cancellationpoint,
637 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
638 // kmp_int32 cncl_kind);
639 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000640 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
641 // kmp_int32 num_teams, kmp_int32 thread_limit);
642 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000643 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
644 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000646 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
647 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
648 // sched, kmp_uint64 grainsize, void *task_dup);
649 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000650 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
651 // num_dims, struct kmp_dim *dims);
652 OMPRTL__kmpc_doacross_init,
653 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
654 OMPRTL__kmpc_doacross_fini,
655 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
656 // *vec);
657 OMPRTL__kmpc_doacross_post,
658 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
659 // *vec);
660 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000661 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
662 // *data);
663 OMPRTL__kmpc_task_reduction_init,
664 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
665 // *d);
666 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000667
668 //
669 // Offloading related calls
670 //
671 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
672 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
673 // *arg_types);
674 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000675 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
676 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
677 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
678 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000679 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
680 OMPRTL__tgt_register_lib,
681 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
682 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000683 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
684 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
685 OMPRTL__tgt_target_data_begin,
686 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
687 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
688 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000689 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
690 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
691 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692};
693
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000694/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
695/// region.
696class CleanupTy final : public EHScopeStack::Cleanup {
697 PrePostActionTy *Action;
698
699public:
700 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
701 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
702 if (!CGF.HaveInsertPoint())
703 return;
704 Action->Exit(CGF);
705 }
706};
707
Hans Wennborg7eb54642015-09-10 17:07:54 +0000708} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000709
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000710void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
711 CodeGenFunction::RunCleanupsScope Scope(CGF);
712 if (PrePostAction) {
713 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
714 Callback(CodeGen, CGF, *PrePostAction);
715 } else {
716 PrePostActionTy Action;
717 Callback(CodeGen, CGF, Action);
718 }
719}
720
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000721/// Check if the combiner is a call to UDR combiner and if it is so return the
722/// UDR decl used for reduction.
723static const OMPDeclareReductionDecl *
724getReductionInit(const Expr *ReductionOp) {
725 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
726 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
727 if (auto *DRE =
728 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
729 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
730 return DRD;
731 return nullptr;
732}
733
734static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
735 const OMPDeclareReductionDecl *DRD,
736 const Expr *InitOp,
737 Address Private, Address Original,
738 QualType Ty) {
739 if (DRD->getInitializer()) {
740 std::pair<llvm::Function *, llvm::Function *> Reduction =
741 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
742 auto *CE = cast<CallExpr>(InitOp);
743 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
744 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
745 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
746 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
747 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
748 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
749 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
750 [=]() -> Address { return Private; });
751 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
752 [=]() -> Address { return Original; });
753 (void)PrivateScope.Privatize();
754 RValue Func = RValue::get(Reduction.second);
755 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
756 CGF.EmitIgnoredExpr(InitOp);
757 } else {
758 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
759 auto *GV = new llvm::GlobalVariable(
760 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
761 llvm::GlobalValue::PrivateLinkage, Init, ".init");
762 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
763 RValue InitRVal;
764 switch (CGF.getEvaluationKind(Ty)) {
765 case TEK_Scalar:
766 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
767 break;
768 case TEK_Complex:
769 InitRVal =
770 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
771 break;
772 case TEK_Aggregate:
773 InitRVal = RValue::getAggregate(LV.getAddress());
774 break;
775 }
776 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
777 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
778 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
779 /*IsInitializer=*/false);
780 }
781}
782
783/// \brief Emit initialization of arrays of complex types.
784/// \param DestAddr Address of the array.
785/// \param Type Type of array.
786/// \param Init Initial expression of array.
787/// \param SrcAddr Address of the original array.
788static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000789 QualType Type, bool EmitDeclareReductionInit,
790 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000791 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000792 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000793 // Perform element-by-element initialization.
794 QualType ElementTy;
795
796 // Drill down to the base element type on both arrays.
797 auto ArrayTy = Type->getAsArrayTypeUnsafe();
798 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
799 DestAddr =
800 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
801 if (DRD)
802 SrcAddr =
803 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
804
805 llvm::Value *SrcBegin = nullptr;
806 if (DRD)
807 SrcBegin = SrcAddr.getPointer();
808 auto DestBegin = DestAddr.getPointer();
809 // Cast from pointer to array type to pointer to single element.
810 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
811 // The basic structure here is a while-do loop.
812 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
813 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
814 auto IsEmpty =
815 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
816 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
817
818 // Enter the loop body, making that address the current address.
819 auto EntryBB = CGF.Builder.GetInsertBlock();
820 CGF.EmitBlock(BodyBB);
821
822 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
823
824 llvm::PHINode *SrcElementPHI = nullptr;
825 Address SrcElementCurrent = Address::invalid();
826 if (DRD) {
827 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
828 "omp.arraycpy.srcElementPast");
829 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
830 SrcElementCurrent =
831 Address(SrcElementPHI,
832 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
833 }
834 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
835 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
836 DestElementPHI->addIncoming(DestBegin, EntryBB);
837 Address DestElementCurrent =
838 Address(DestElementPHI,
839 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
840
841 // Emit copy.
842 {
843 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000844 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000845 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
846 SrcElementCurrent, ElementTy);
847 } else
848 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
849 /*IsInitializer=*/false);
850 }
851
852 if (DRD) {
853 // Shift the address forward by one element.
854 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
855 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
856 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
857 }
858
859 // Shift the address forward by one element.
860 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
861 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
862 // Check whether we've reached the end.
863 auto Done =
864 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
865 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
866 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
867
868 // Done.
869 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
870}
871
872LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000873 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000874}
875
876LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
877 const Expr *E) {
878 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
879 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
880 return LValue();
881}
882
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000883void ReductionCodeGen::emitAggregateInitialization(
884 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
885 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000886 // Emit VarDecl with copy init for arrays.
887 // Get the address of the original variable captured in current
888 // captured region.
889 auto *PrivateVD =
890 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000891 bool EmitDeclareReductionInit =
892 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000893 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000894 EmitDeclareReductionInit,
895 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
896 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000897 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000898}
899
900ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
901 ArrayRef<const Expr *> Privates,
902 ArrayRef<const Expr *> ReductionOps) {
903 ClausesData.reserve(Shareds.size());
904 SharedAddresses.reserve(Shareds.size());
905 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000906 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000907 auto IPriv = Privates.begin();
908 auto IRed = ReductionOps.begin();
909 for (const auto *Ref : Shareds) {
910 ClausesData.emplace_back(Ref, *IPriv, *IRed);
911 std::advance(IPriv, 1);
912 std::advance(IRed, 1);
913 }
914}
915
916void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
917 assert(SharedAddresses.size() == N &&
918 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000919 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
920 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
921 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000922}
923
924void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
925 auto *PrivateVD =
926 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
927 QualType PrivateType = PrivateVD->getType();
928 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000929 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930 Sizes.emplace_back(
931 CGF.getTypeSize(
932 SharedAddresses[N].first.getType().getNonReferenceType()),
933 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000934 return;
935 }
936 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000937 llvm::Value *SizeInChars;
938 llvm::Type *ElemType =
939 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
940 ->getElementType();
941 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 if (AsArraySection) {
943 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
944 SharedAddresses[N].first.getPointer());
945 Size = CGF.Builder.CreateNUWAdd(
946 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000949 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000951 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000953 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 CodeGenFunction::OpaqueValueMapping OpaqueMap(
955 CGF,
956 cast<OpaqueValueExpr>(
957 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
958 RValue::get(Size));
959 CGF.EmitVariablyModifiedType(PrivateType);
960}
961
962void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
963 llvm::Value *Size) {
964 auto *PrivateVD =
965 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
966 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000967 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000968 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000969 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 "items.");
971 return;
972 }
973 CodeGenFunction::OpaqueValueMapping OpaqueMap(
974 CGF,
975 cast<OpaqueValueExpr>(
976 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
977 RValue::get(Size));
978 CGF.EmitVariablyModifiedType(PrivateType);
979}
980
981void ReductionCodeGen::emitInitialization(
982 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
983 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
984 assert(SharedAddresses.size() > N && "No variable was generated");
985 auto *PrivateVD =
986 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
987 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
988 QualType PrivateType = PrivateVD->getType();
989 PrivateAddr = CGF.Builder.CreateElementBitCast(
990 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
991 QualType SharedType = SharedAddresses[N].first.getType();
992 SharedLVal = CGF.MakeAddrLValue(
993 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
994 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +0000995 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000996 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000997 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1000 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1001 PrivateAddr, SharedLVal.getAddress(),
1002 SharedLVal.getType());
1003 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1004 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1005 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1006 PrivateVD->getType().getQualifiers(),
1007 /*IsInitializer=*/false);
1008 }
1009}
1010
1011bool ReductionCodeGen::needCleanups(unsigned N) {
1012 auto *PrivateVD =
1013 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1014 QualType PrivateType = PrivateVD->getType();
1015 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1016 return DTorKind != QualType::DK_none;
1017}
1018
1019void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1020 Address PrivateAddr) {
1021 auto *PrivateVD =
1022 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1023 QualType PrivateType = PrivateVD->getType();
1024 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1025 if (needCleanups(N)) {
1026 PrivateAddr = CGF.Builder.CreateElementBitCast(
1027 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1028 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1029 }
1030}
1031
1032static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1033 LValue BaseLV) {
1034 BaseTy = BaseTy.getNonReferenceType();
1035 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1036 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1037 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1038 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1039 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001040 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1041 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001042 }
1043 BaseTy = BaseTy->getPointeeType();
1044 }
1045 return CGF.MakeAddrLValue(
1046 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1047 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001048 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001049 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001050}
1051
1052static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1053 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1054 llvm::Value *Addr) {
1055 Address Tmp = Address::invalid();
1056 Address TopTmp = Address::invalid();
1057 Address MostTopTmp = Address::invalid();
1058 BaseTy = BaseTy.getNonReferenceType();
1059 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1060 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1061 Tmp = CGF.CreateMemTemp(BaseTy);
1062 if (TopTmp.isValid())
1063 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1064 else
1065 MostTopTmp = Tmp;
1066 TopTmp = Tmp;
1067 BaseTy = BaseTy->getPointeeType();
1068 }
1069 llvm::Type *Ty = BaseLVType;
1070 if (Tmp.isValid())
1071 Ty = Tmp.getElementType();
1072 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1073 if (Tmp.isValid()) {
1074 CGF.Builder.CreateStore(Addr, Tmp);
1075 return MostTopTmp;
1076 }
1077 return Address(Addr, BaseLVAlignment);
1078}
1079
1080Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1081 Address PrivateAddr) {
1082 const DeclRefExpr *DE;
1083 const VarDecl *OrigVD = nullptr;
1084 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1085 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1086 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1087 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1088 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1089 Base = TempASE->getBase()->IgnoreParenImpCasts();
1090 DE = cast<DeclRefExpr>(Base);
1091 OrigVD = cast<VarDecl>(DE->getDecl());
1092 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1093 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1094 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1095 Base = TempASE->getBase()->IgnoreParenImpCasts();
1096 DE = cast<DeclRefExpr>(Base);
1097 OrigVD = cast<VarDecl>(DE->getDecl());
1098 }
1099 if (OrigVD) {
1100 BaseDecls.emplace_back(OrigVD);
1101 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1102 LValue BaseLValue =
1103 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1104 OriginalBaseLValue);
1105 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1106 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1107 llvm::Value *Ptr =
1108 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1109 return castToBase(CGF, OrigVD->getType(),
1110 SharedAddresses[N].first.getType(),
1111 OriginalBaseLValue.getPointer()->getType(),
1112 OriginalBaseLValue.getAlignment(), Ptr);
1113 }
1114 BaseDecls.emplace_back(
1115 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1116 return PrivateAddr;
1117}
1118
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001119bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1120 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1121 return DRD && DRD->getInitializer();
1122}
1123
Alexey Bataev18095712014-10-10 12:19:54 +00001124LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001125 return CGF.EmitLoadOfPointerLValue(
1126 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1127 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001128}
1129
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001130void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001131 if (!CGF.HaveInsertPoint())
1132 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001133 // 1.2.2 OpenMP Language Terminology
1134 // Structured block - An executable statement with a single entry at the
1135 // top and a single exit at the bottom.
1136 // The point of exit cannot be a branch out of the structured block.
1137 // longjmp() and throw() must not violate the entry/exit criteria.
1138 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001139 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001140 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001141}
1142
Alexey Bataev62b63b12015-03-10 07:28:44 +00001143LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1144 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001145 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1146 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001147 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001148}
1149
Alexey Bataev9959db52014-05-06 10:08:46 +00001150CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001151 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001152 IdentTy = llvm::StructType::create(
1153 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1154 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001155 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001156 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001157
1158 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001159}
1160
Alexey Bataev91797552015-03-18 04:13:55 +00001161void CGOpenMPRuntime::clear() {
1162 InternalVars.clear();
1163}
1164
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001165static llvm::Function *
1166emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1167 const Expr *CombinerInitializer, const VarDecl *In,
1168 const VarDecl *Out, bool IsCombiner) {
1169 // void .omp_combiner.(Ty *in, Ty *out);
1170 auto &C = CGM.getContext();
1171 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1172 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001173 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001174 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001175 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001176 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001177 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001178 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001179 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001180 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001181 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1182 auto *Fn = llvm::Function::Create(
1183 FnTy, llvm::GlobalValue::InternalLinkage,
1184 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1185 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001186 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001187 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001188 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001189 CodeGenFunction CGF(CGM);
1190 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1191 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1192 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1193 CodeGenFunction::OMPPrivateScope Scope(CGF);
1194 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1195 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1196 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1197 .getAddress();
1198 });
1199 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1200 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1201 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1202 .getAddress();
1203 });
1204 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001205 if (!IsCombiner && Out->hasInit() &&
1206 !CGF.isTrivialInitializer(Out->getInit())) {
1207 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1208 Out->getType().getQualifiers(),
1209 /*IsInitializer=*/true);
1210 }
1211 if (CombinerInitializer)
1212 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001213 Scope.ForceCleanup();
1214 CGF.FinishFunction();
1215 return Fn;
1216}
1217
1218void CGOpenMPRuntime::emitUserDefinedReduction(
1219 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1220 if (UDRMap.count(D) > 0)
1221 return;
1222 auto &C = CGM.getContext();
1223 if (!In || !Out) {
1224 In = &C.Idents.get("omp_in");
1225 Out = &C.Idents.get("omp_out");
1226 }
1227 llvm::Function *Combiner = emitCombinerOrInitializer(
1228 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1229 cast<VarDecl>(D->lookup(Out).front()),
1230 /*IsCombiner=*/true);
1231 llvm::Function *Initializer = nullptr;
1232 if (auto *Init = D->getInitializer()) {
1233 if (!Priv || !Orig) {
1234 Priv = &C.Idents.get("omp_priv");
1235 Orig = &C.Idents.get("omp_orig");
1236 }
1237 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001238 CGM, D->getType(),
1239 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1240 : nullptr,
1241 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001242 cast<VarDecl>(D->lookup(Priv).front()),
1243 /*IsCombiner=*/false);
1244 }
1245 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1246 if (CGF) {
1247 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1248 Decls.second.push_back(D);
1249 }
1250}
1251
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001252std::pair<llvm::Function *, llvm::Function *>
1253CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1254 auto I = UDRMap.find(D);
1255 if (I != UDRMap.end())
1256 return I->second;
1257 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1258 return UDRMap.lookup(D);
1259}
1260
John McCall7f416cc2015-09-08 08:05:57 +00001261// Layout information for ident_t.
1262static CharUnits getIdentAlign(CodeGenModule &CGM) {
1263 return CGM.getPointerAlign();
1264}
1265static CharUnits getIdentSize(CodeGenModule &CGM) {
1266 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1267 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1268}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001269static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001270 // All the fields except the last are i32, so this works beautifully.
1271 return unsigned(Field) * CharUnits::fromQuantity(4);
1272}
1273static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001274 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001275 const llvm::Twine &Name = "") {
1276 auto Offset = getOffsetOfIdentField(Field);
1277 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1278}
1279
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001280static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1281 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1282 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1283 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001284 assert(ThreadIDVar->getType()->isPointerType() &&
1285 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001286 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001287 bool HasCancel = false;
1288 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1289 HasCancel = OPD->hasCancel();
1290 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1291 HasCancel = OPSD->hasCancel();
1292 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1293 HasCancel = OPFD->hasCancel();
1294 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001295 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001296 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001297 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001298}
1299
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001300llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1301 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1302 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1303 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1304 return emitParallelOrTeamsOutlinedFunction(
1305 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1306}
1307
1308llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1309 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1310 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1311 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1312 return emitParallelOrTeamsOutlinedFunction(
1313 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1314}
1315
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001316llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1317 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001318 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1319 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1320 bool Tied, unsigned &NumberOfParts) {
1321 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1322 PrePostActionTy &) {
1323 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1324 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1325 llvm::Value *TaskArgs[] = {
1326 UpLoc, ThreadID,
1327 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1328 TaskTVar->getType()->castAs<PointerType>())
1329 .getPointer()};
1330 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1331 };
1332 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1333 UntiedCodeGen);
1334 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001335 assert(!ThreadIDVar->getType()->isPointerType() &&
1336 "thread id variable must be of type kmp_int32 for tasks");
1337 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001338 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001339 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001340 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1341 InnermostKind,
1342 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001343 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001344 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1345 if (!Tied)
1346 NumberOfParts = Action.getNumberOfParts();
1347 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001348}
1349
Alexey Bataev50b3c952016-02-19 10:38:26 +00001350Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001351 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001352 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001353 if (!Entry) {
1354 if (!DefaultOpenMPPSource) {
1355 // Initialize default location for psource field of ident_t structure of
1356 // all ident_t objects. Format is ";file;function;line;column;;".
1357 // Taken from
1358 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1359 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001360 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001361 DefaultOpenMPPSource =
1362 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1363 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001364
John McCall23c9dc62016-11-28 22:18:27 +00001365 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001366 auto fields = builder.beginStruct(IdentTy);
1367 fields.addInt(CGM.Int32Ty, 0);
1368 fields.addInt(CGM.Int32Ty, Flags);
1369 fields.addInt(CGM.Int32Ty, 0);
1370 fields.addInt(CGM.Int32Ty, 0);
1371 fields.add(DefaultOpenMPPSource);
1372 auto DefaultOpenMPLocation =
1373 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1374 llvm::GlobalValue::PrivateLinkage);
1375 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1376
John McCall7f416cc2015-09-08 08:05:57 +00001377 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001378 }
John McCall7f416cc2015-09-08 08:05:57 +00001379 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001380}
1381
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001382llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1383 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001384 unsigned Flags) {
1385 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001386 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001387 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001388 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001389 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001390
1391 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1392
John McCall7f416cc2015-09-08 08:05:57 +00001393 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001394 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1395 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001396 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1397
Alexander Musmanc6388682014-12-15 07:07:06 +00001398 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1399 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001400 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001401 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001402 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1403 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001404 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001405 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001406 LocValue = AI;
1407
1408 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1409 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001410 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001411 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001412 }
1413
1414 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001415 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001416
Alexey Bataevf002aca2014-05-30 05:48:40 +00001417 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1418 if (OMPDebugLoc == nullptr) {
1419 SmallString<128> Buffer2;
1420 llvm::raw_svector_ostream OS2(Buffer2);
1421 // Build debug location
1422 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1423 OS2 << ";" << PLoc.getFilename() << ";";
1424 if (const FunctionDecl *FD =
1425 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1426 OS2 << FD->getQualifiedNameAsString();
1427 }
1428 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1429 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1430 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001431 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001432 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001433 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1434
John McCall7f416cc2015-09-08 08:05:57 +00001435 // Our callers always pass this to a runtime function, so for
1436 // convenience, go ahead and return a naked pointer.
1437 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001438}
1439
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001440llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1441 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001442 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1443
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001444 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001445 // Check whether we've already cached a load of the thread id in this
1446 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001447 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001448 if (I != OpenMPLocThreadIDMap.end()) {
1449 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001450 if (ThreadID != nullptr)
1451 return ThreadID;
1452 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001453 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001454 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1455 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001456 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001457 if (auto *OMPRegionInfo =
1458 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1459 if (OMPRegionInfo->getThreadIDVariable()) {
1460 // Check if this an outlined function with thread id passed as argument.
1461 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1462 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1463 // If value loaded in entry block, cache it and use it everywhere in
1464 // function.
1465 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1466 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1467 Elem.second.ThreadID = ThreadID;
1468 }
1469 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001470 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001471 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001472 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001473
1474 // This is not an outlined function region - need to call __kmpc_int32
1475 // kmpc_global_thread_num(ident_t *loc).
1476 // Generate thread id value and cache this value for use across the
1477 // function.
1478 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1479 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001480 auto *Call = CGF.Builder.CreateCall(
1481 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1482 emitUpdateLocation(CGF, Loc));
1483 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001484 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001485 Elem.second.ThreadID = Call;
1486 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001487}
1488
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001489void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001490 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001491 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1492 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001493 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1494 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1495 UDRMap.erase(D);
1496 }
1497 FunctionUDRMap.erase(CGF.CurFn);
1498 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001499}
1500
1501llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001502 if (!IdentTy) {
1503 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001504 return llvm::PointerType::getUnqual(IdentTy);
1505}
1506
1507llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001508 if (!Kmpc_MicroTy) {
1509 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1510 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1511 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1512 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1513 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001514 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1515}
1516
1517llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001518CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001519 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001520 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001521 case OMPRTL__kmpc_fork_call: {
1522 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1523 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001524 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1525 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001526 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001527 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001528 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1529 break;
1530 }
1531 case OMPRTL__kmpc_global_thread_num: {
1532 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001533 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001534 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001535 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001536 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1537 break;
1538 }
Alexey Bataev97720002014-11-11 04:05:39 +00001539 case OMPRTL__kmpc_threadprivate_cached: {
1540 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1541 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1542 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1543 CGM.VoidPtrTy, CGM.SizeTy,
1544 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1545 llvm::FunctionType *FnTy =
1546 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1547 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1548 break;
1549 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001550 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001551 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1552 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001553 llvm::Type *TypeParams[] = {
1554 getIdentTyPointerTy(), CGM.Int32Ty,
1555 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1556 llvm::FunctionType *FnTy =
1557 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1558 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1559 break;
1560 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001561 case OMPRTL__kmpc_critical_with_hint: {
1562 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1563 // kmp_critical_name *crit, uintptr_t hint);
1564 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1565 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1566 CGM.IntPtrTy};
1567 llvm::FunctionType *FnTy =
1568 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1570 break;
1571 }
Alexey Bataev97720002014-11-11 04:05:39 +00001572 case OMPRTL__kmpc_threadprivate_register: {
1573 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1574 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1575 // typedef void *(*kmpc_ctor)(void *);
1576 auto KmpcCtorTy =
1577 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1578 /*isVarArg*/ false)->getPointerTo();
1579 // typedef void *(*kmpc_cctor)(void *, void *);
1580 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1581 auto KmpcCopyCtorTy =
1582 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1583 /*isVarArg*/ false)->getPointerTo();
1584 // typedef void (*kmpc_dtor)(void *);
1585 auto KmpcDtorTy =
1586 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1587 ->getPointerTo();
1588 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1589 KmpcCopyCtorTy, KmpcDtorTy};
1590 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1591 /*isVarArg*/ false);
1592 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1593 break;
1594 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001595 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001596 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1597 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001598 llvm::Type *TypeParams[] = {
1599 getIdentTyPointerTy(), CGM.Int32Ty,
1600 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1601 llvm::FunctionType *FnTy =
1602 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1603 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1604 break;
1605 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001606 case OMPRTL__kmpc_cancel_barrier: {
1607 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1608 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001609 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1610 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001611 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1612 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001613 break;
1614 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001615 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001616 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001617 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1618 llvm::FunctionType *FnTy =
1619 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1620 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1621 break;
1622 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001623 case OMPRTL__kmpc_for_static_fini: {
1624 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1625 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1626 llvm::FunctionType *FnTy =
1627 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1628 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1629 break;
1630 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001631 case OMPRTL__kmpc_push_num_threads: {
1632 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1633 // kmp_int32 num_threads)
1634 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1635 CGM.Int32Ty};
1636 llvm::FunctionType *FnTy =
1637 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1638 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1639 break;
1640 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001641 case OMPRTL__kmpc_serialized_parallel: {
1642 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1643 // global_tid);
1644 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1645 llvm::FunctionType *FnTy =
1646 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1647 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1648 break;
1649 }
1650 case OMPRTL__kmpc_end_serialized_parallel: {
1651 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1652 // global_tid);
1653 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1654 llvm::FunctionType *FnTy =
1655 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1656 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1657 break;
1658 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001659 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001660 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001661 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1662 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001663 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001664 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1665 break;
1666 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001667 case OMPRTL__kmpc_master: {
1668 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1669 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1670 llvm::FunctionType *FnTy =
1671 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1672 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1673 break;
1674 }
1675 case OMPRTL__kmpc_end_master: {
1676 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1677 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1678 llvm::FunctionType *FnTy =
1679 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1680 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1681 break;
1682 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001683 case OMPRTL__kmpc_omp_taskyield: {
1684 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1685 // int end_part);
1686 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1687 llvm::FunctionType *FnTy =
1688 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1689 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1690 break;
1691 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001692 case OMPRTL__kmpc_single: {
1693 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1694 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1695 llvm::FunctionType *FnTy =
1696 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1697 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1698 break;
1699 }
1700 case OMPRTL__kmpc_end_single: {
1701 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1702 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1703 llvm::FunctionType *FnTy =
1704 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1705 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1706 break;
1707 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001708 case OMPRTL__kmpc_omp_task_alloc: {
1709 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1710 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1711 // kmp_routine_entry_t *task_entry);
1712 assert(KmpRoutineEntryPtrTy != nullptr &&
1713 "Type kmp_routine_entry_t must be created.");
1714 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1715 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1716 // Return void * and then cast to particular kmp_task_t type.
1717 llvm::FunctionType *FnTy =
1718 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1719 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1720 break;
1721 }
1722 case OMPRTL__kmpc_omp_task: {
1723 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1724 // *new_task);
1725 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1726 CGM.VoidPtrTy};
1727 llvm::FunctionType *FnTy =
1728 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1729 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1730 break;
1731 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001732 case OMPRTL__kmpc_copyprivate: {
1733 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001734 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001735 // kmp_int32 didit);
1736 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1737 auto *CpyFnTy =
1738 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001740 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1741 CGM.Int32Ty};
1742 llvm::FunctionType *FnTy =
1743 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1745 break;
1746 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001747 case OMPRTL__kmpc_reduce: {
1748 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1749 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1750 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1751 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1752 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1753 /*isVarArg=*/false);
1754 llvm::Type *TypeParams[] = {
1755 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1756 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1757 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1758 llvm::FunctionType *FnTy =
1759 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1760 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1761 break;
1762 }
1763 case OMPRTL__kmpc_reduce_nowait: {
1764 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1765 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1766 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1767 // *lck);
1768 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1769 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1770 /*isVarArg=*/false);
1771 llvm::Type *TypeParams[] = {
1772 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1773 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1774 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1775 llvm::FunctionType *FnTy =
1776 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1778 break;
1779 }
1780 case OMPRTL__kmpc_end_reduce: {
1781 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1782 // kmp_critical_name *lck);
1783 llvm::Type *TypeParams[] = {
1784 getIdentTyPointerTy(), CGM.Int32Ty,
1785 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1786 llvm::FunctionType *FnTy =
1787 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1788 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1789 break;
1790 }
1791 case OMPRTL__kmpc_end_reduce_nowait: {
1792 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1793 // kmp_critical_name *lck);
1794 llvm::Type *TypeParams[] = {
1795 getIdentTyPointerTy(), CGM.Int32Ty,
1796 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1797 llvm::FunctionType *FnTy =
1798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1799 RTLFn =
1800 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1801 break;
1802 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001803 case OMPRTL__kmpc_omp_task_begin_if0: {
1804 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1805 // *new_task);
1806 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1807 CGM.VoidPtrTy};
1808 llvm::FunctionType *FnTy =
1809 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1810 RTLFn =
1811 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1812 break;
1813 }
1814 case OMPRTL__kmpc_omp_task_complete_if0: {
1815 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1816 // *new_task);
1817 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1818 CGM.VoidPtrTy};
1819 llvm::FunctionType *FnTy =
1820 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1821 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1822 /*Name=*/"__kmpc_omp_task_complete_if0");
1823 break;
1824 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001825 case OMPRTL__kmpc_ordered: {
1826 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1827 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1828 llvm::FunctionType *FnTy =
1829 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1830 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1831 break;
1832 }
1833 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001834 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001835 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1836 llvm::FunctionType *FnTy =
1837 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1838 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1839 break;
1840 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001841 case OMPRTL__kmpc_omp_taskwait: {
1842 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1843 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1844 llvm::FunctionType *FnTy =
1845 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1846 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1847 break;
1848 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001849 case OMPRTL__kmpc_taskgroup: {
1850 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1851 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1852 llvm::FunctionType *FnTy =
1853 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1854 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1855 break;
1856 }
1857 case OMPRTL__kmpc_end_taskgroup: {
1858 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1859 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1860 llvm::FunctionType *FnTy =
1861 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1862 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1863 break;
1864 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001865 case OMPRTL__kmpc_push_proc_bind: {
1866 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1867 // int proc_bind)
1868 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1869 llvm::FunctionType *FnTy =
1870 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1871 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1872 break;
1873 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001874 case OMPRTL__kmpc_omp_task_with_deps: {
1875 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1876 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1877 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1878 llvm::Type *TypeParams[] = {
1879 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1880 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1881 llvm::FunctionType *FnTy =
1882 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1883 RTLFn =
1884 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1885 break;
1886 }
1887 case OMPRTL__kmpc_omp_wait_deps: {
1888 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1889 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1890 // kmp_depend_info_t *noalias_dep_list);
1891 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1892 CGM.Int32Ty, CGM.VoidPtrTy,
1893 CGM.Int32Ty, CGM.VoidPtrTy};
1894 llvm::FunctionType *FnTy =
1895 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1896 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1897 break;
1898 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001899 case OMPRTL__kmpc_cancellationpoint: {
1900 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1901 // global_tid, kmp_int32 cncl_kind)
1902 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1903 llvm::FunctionType *FnTy =
1904 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1905 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1906 break;
1907 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001908 case OMPRTL__kmpc_cancel: {
1909 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1910 // kmp_int32 cncl_kind)
1911 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1912 llvm::FunctionType *FnTy =
1913 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1914 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1915 break;
1916 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001917 case OMPRTL__kmpc_push_num_teams: {
1918 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1919 // kmp_int32 num_teams, kmp_int32 num_threads)
1920 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1921 CGM.Int32Ty};
1922 llvm::FunctionType *FnTy =
1923 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1924 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1925 break;
1926 }
1927 case OMPRTL__kmpc_fork_teams: {
1928 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1929 // microtask, ...);
1930 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1931 getKmpc_MicroPointerTy()};
1932 llvm::FunctionType *FnTy =
1933 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1934 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1935 break;
1936 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001937 case OMPRTL__kmpc_taskloop: {
1938 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1939 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1940 // sched, kmp_uint64 grainsize, void *task_dup);
1941 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1942 CGM.IntTy,
1943 CGM.VoidPtrTy,
1944 CGM.IntTy,
1945 CGM.Int64Ty->getPointerTo(),
1946 CGM.Int64Ty->getPointerTo(),
1947 CGM.Int64Ty,
1948 CGM.IntTy,
1949 CGM.IntTy,
1950 CGM.Int64Ty,
1951 CGM.VoidPtrTy};
1952 llvm::FunctionType *FnTy =
1953 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1954 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1955 break;
1956 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001957 case OMPRTL__kmpc_doacross_init: {
1958 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1959 // num_dims, struct kmp_dim *dims);
1960 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1961 CGM.Int32Ty,
1962 CGM.Int32Ty,
1963 CGM.VoidPtrTy};
1964 llvm::FunctionType *FnTy =
1965 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1966 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1967 break;
1968 }
1969 case OMPRTL__kmpc_doacross_fini: {
1970 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1971 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1972 llvm::FunctionType *FnTy =
1973 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1974 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1975 break;
1976 }
1977 case OMPRTL__kmpc_doacross_post: {
1978 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1979 // *vec);
1980 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1981 CGM.Int64Ty->getPointerTo()};
1982 llvm::FunctionType *FnTy =
1983 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1984 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1985 break;
1986 }
1987 case OMPRTL__kmpc_doacross_wait: {
1988 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1989 // *vec);
1990 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1991 CGM.Int64Ty->getPointerTo()};
1992 llvm::FunctionType *FnTy =
1993 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1994 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1995 break;
1996 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001997 case OMPRTL__kmpc_task_reduction_init: {
1998 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1999 // *data);
2000 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2001 llvm::FunctionType *FnTy =
2002 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2003 RTLFn =
2004 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2005 break;
2006 }
2007 case OMPRTL__kmpc_task_reduction_get_th_data: {
2008 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2009 // *d);
2010 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2011 llvm::FunctionType *FnTy =
2012 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2013 RTLFn = CGM.CreateRuntimeFunction(
2014 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2015 break;
2016 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002017 case OMPRTL__tgt_target: {
2018 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2019 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2020 // *arg_types);
2021 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2022 CGM.VoidPtrTy,
2023 CGM.Int32Ty,
2024 CGM.VoidPtrPtrTy,
2025 CGM.VoidPtrPtrTy,
2026 CGM.SizeTy->getPointerTo(),
2027 CGM.Int32Ty->getPointerTo()};
2028 llvm::FunctionType *FnTy =
2029 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2030 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2031 break;
2032 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002033 case OMPRTL__tgt_target_teams: {
2034 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2035 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2036 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2037 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2038 CGM.VoidPtrTy,
2039 CGM.Int32Ty,
2040 CGM.VoidPtrPtrTy,
2041 CGM.VoidPtrPtrTy,
2042 CGM.SizeTy->getPointerTo(),
2043 CGM.Int32Ty->getPointerTo(),
2044 CGM.Int32Ty,
2045 CGM.Int32Ty};
2046 llvm::FunctionType *FnTy =
2047 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2048 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2049 break;
2050 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002051 case OMPRTL__tgt_register_lib: {
2052 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2053 QualType ParamTy =
2054 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2055 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2056 llvm::FunctionType *FnTy =
2057 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2058 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2059 break;
2060 }
2061 case OMPRTL__tgt_unregister_lib: {
2062 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2063 QualType ParamTy =
2064 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2065 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2066 llvm::FunctionType *FnTy =
2067 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2068 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2069 break;
2070 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002071 case OMPRTL__tgt_target_data_begin: {
2072 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2073 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2074 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2075 CGM.Int32Ty,
2076 CGM.VoidPtrPtrTy,
2077 CGM.VoidPtrPtrTy,
2078 CGM.SizeTy->getPointerTo(),
2079 CGM.Int32Ty->getPointerTo()};
2080 llvm::FunctionType *FnTy =
2081 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2082 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2083 break;
2084 }
2085 case OMPRTL__tgt_target_data_end: {
2086 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2087 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2088 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2089 CGM.Int32Ty,
2090 CGM.VoidPtrPtrTy,
2091 CGM.VoidPtrPtrTy,
2092 CGM.SizeTy->getPointerTo(),
2093 CGM.Int32Ty->getPointerTo()};
2094 llvm::FunctionType *FnTy =
2095 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2096 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2097 break;
2098 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002099 case OMPRTL__tgt_target_data_update: {
2100 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2101 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2102 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2103 CGM.Int32Ty,
2104 CGM.VoidPtrPtrTy,
2105 CGM.VoidPtrPtrTy,
2106 CGM.SizeTy->getPointerTo(),
2107 CGM.Int32Ty->getPointerTo()};
2108 llvm::FunctionType *FnTy =
2109 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2110 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2111 break;
2112 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002113 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002114 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002115 return RTLFn;
2116}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002117
Alexander Musman21212e42015-03-13 10:38:23 +00002118llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2119 bool IVSigned) {
2120 assert((IVSize == 32 || IVSize == 64) &&
2121 "IV size is not compatible with the omp runtime");
2122 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2123 : "__kmpc_for_static_init_4u")
2124 : (IVSigned ? "__kmpc_for_static_init_8"
2125 : "__kmpc_for_static_init_8u");
2126 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2127 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2128 llvm::Type *TypeParams[] = {
2129 getIdentTyPointerTy(), // loc
2130 CGM.Int32Ty, // tid
2131 CGM.Int32Ty, // schedtype
2132 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2133 PtrTy, // p_lower
2134 PtrTy, // p_upper
2135 PtrTy, // p_stride
2136 ITy, // incr
2137 ITy // chunk
2138 };
2139 llvm::FunctionType *FnTy =
2140 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2141 return CGM.CreateRuntimeFunction(FnTy, Name);
2142}
2143
Alexander Musman92bdaab2015-03-12 13:37:50 +00002144llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2145 bool IVSigned) {
2146 assert((IVSize == 32 || IVSize == 64) &&
2147 "IV size is not compatible with the omp runtime");
2148 auto Name =
2149 IVSize == 32
2150 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2151 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2152 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2153 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2154 CGM.Int32Ty, // tid
2155 CGM.Int32Ty, // schedtype
2156 ITy, // lower
2157 ITy, // upper
2158 ITy, // stride
2159 ITy // chunk
2160 };
2161 llvm::FunctionType *FnTy =
2162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2163 return CGM.CreateRuntimeFunction(FnTy, Name);
2164}
2165
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002166llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2167 bool IVSigned) {
2168 assert((IVSize == 32 || IVSize == 64) &&
2169 "IV size is not compatible with the omp runtime");
2170 auto Name =
2171 IVSize == 32
2172 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2173 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2174 llvm::Type *TypeParams[] = {
2175 getIdentTyPointerTy(), // loc
2176 CGM.Int32Ty, // tid
2177 };
2178 llvm::FunctionType *FnTy =
2179 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2180 return CGM.CreateRuntimeFunction(FnTy, Name);
2181}
2182
Alexander Musman92bdaab2015-03-12 13:37:50 +00002183llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2184 bool IVSigned) {
2185 assert((IVSize == 32 || IVSize == 64) &&
2186 "IV size is not compatible with the omp runtime");
2187 auto Name =
2188 IVSize == 32
2189 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2190 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2191 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2192 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2193 llvm::Type *TypeParams[] = {
2194 getIdentTyPointerTy(), // loc
2195 CGM.Int32Ty, // tid
2196 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2197 PtrTy, // p_lower
2198 PtrTy, // p_upper
2199 PtrTy // p_stride
2200 };
2201 llvm::FunctionType *FnTy =
2202 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2203 return CGM.CreateRuntimeFunction(FnTy, Name);
2204}
2205
Alexey Bataev97720002014-11-11 04:05:39 +00002206llvm::Constant *
2207CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002208 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2209 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002210 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002211 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002212 Twine(CGM.getMangledName(VD)) + ".cache.");
2213}
2214
John McCall7f416cc2015-09-08 08:05:57 +00002215Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2216 const VarDecl *VD,
2217 Address VDAddr,
2218 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002219 if (CGM.getLangOpts().OpenMPUseTLS &&
2220 CGM.getContext().getTargetInfo().isTLSSupported())
2221 return VDAddr;
2222
John McCall7f416cc2015-09-08 08:05:57 +00002223 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002224 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002225 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2226 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002227 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2228 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002229 return Address(CGF.EmitRuntimeCall(
2230 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2231 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002232}
2233
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002234void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002235 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002236 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2237 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2238 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002239 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2240 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002241 OMPLoc);
2242 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2243 // to register constructor/destructor for variable.
2244 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002245 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2246 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002247 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002248 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002249 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002250}
2251
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002252llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002253 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002254 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002255 if (CGM.getLangOpts().OpenMPUseTLS &&
2256 CGM.getContext().getTargetInfo().isTLSSupported())
2257 return nullptr;
2258
Alexey Bataev97720002014-11-11 04:05:39 +00002259 VD = VD->getDefinition(CGM.getContext());
2260 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2261 ThreadPrivateWithDefinition.insert(VD);
2262 QualType ASTTy = VD->getType();
2263
2264 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2265 auto Init = VD->getAnyInitializer();
2266 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2267 // Generate function that re-emits the declaration's initializer into the
2268 // threadprivate copy of the variable VD
2269 CodeGenFunction CtorCGF(CGM);
2270 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002271 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2272 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002273 Args.push_back(&Dst);
2274
John McCallc56a8b32016-03-11 04:30:31 +00002275 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2276 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002277 auto FTy = CGM.getTypes().GetFunctionType(FI);
2278 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002279 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002280 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2281 Args, SourceLocation());
2282 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002283 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002284 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002285 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2286 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2287 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002288 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2289 /*IsInitializer=*/true);
2290 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002291 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002292 CGM.getContext().VoidPtrTy, Dst.getLocation());
2293 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2294 CtorCGF.FinishFunction();
2295 Ctor = Fn;
2296 }
2297 if (VD->getType().isDestructedType() != QualType::DK_none) {
2298 // Generate function that emits destructor call for the threadprivate copy
2299 // of the variable VD
2300 CodeGenFunction DtorCGF(CGM);
2301 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002302 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2303 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002304 Args.push_back(&Dst);
2305
John McCallc56a8b32016-03-11 04:30:31 +00002306 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2307 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002308 auto FTy = CGM.getTypes().GetFunctionType(FI);
2309 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002310 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002311 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002312 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2313 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002314 // Create a scope with an artificial location for the body of this function.
2315 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002316 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2317 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002318 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2319 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002320 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2321 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2322 DtorCGF.FinishFunction();
2323 Dtor = Fn;
2324 }
2325 // Do not emit init function if it is not required.
2326 if (!Ctor && !Dtor)
2327 return nullptr;
2328
2329 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2330 auto CopyCtorTy =
2331 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2332 /*isVarArg=*/false)->getPointerTo();
2333 // Copying constructor for the threadprivate variable.
2334 // Must be NULL - reserved by runtime, but currently it requires that this
2335 // parameter is always NULL. Otherwise it fires assertion.
2336 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2337 if (Ctor == nullptr) {
2338 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2339 /*isVarArg=*/false)->getPointerTo();
2340 Ctor = llvm::Constant::getNullValue(CtorTy);
2341 }
2342 if (Dtor == nullptr) {
2343 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2344 /*isVarArg=*/false)->getPointerTo();
2345 Dtor = llvm::Constant::getNullValue(DtorTy);
2346 }
2347 if (!CGF) {
2348 auto InitFunctionTy =
2349 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2350 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002351 InitFunctionTy, ".__omp_threadprivate_init_.",
2352 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002353 CodeGenFunction InitCGF(CGM);
2354 FunctionArgList ArgList;
2355 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2356 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2357 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002358 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002359 InitCGF.FinishFunction();
2360 return InitFunction;
2361 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002362 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002363 }
2364 return nullptr;
2365}
2366
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002367Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2368 QualType VarType,
2369 StringRef Name) {
2370 llvm::Twine VarName(Name, ".artificial.");
2371 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2372 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2373 llvm::Value *Args[] = {
2374 emitUpdateLocation(CGF, SourceLocation()),
2375 getThreadID(CGF, SourceLocation()),
2376 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2377 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2378 /*IsSigned=*/false),
2379 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2380 return Address(
2381 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2382 CGF.EmitRuntimeCall(
2383 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2384 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2385 CGM.getPointerAlign());
2386}
2387
Alexey Bataev1d677132015-04-22 13:57:31 +00002388/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2389/// function. Here is the logic:
2390/// if (Cond) {
2391/// ThenGen();
2392/// } else {
2393/// ElseGen();
2394/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002395void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2396 const RegionCodeGenTy &ThenGen,
2397 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002398 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2399
2400 // If the condition constant folds and can be elided, try to avoid emitting
2401 // the condition and the dead arm of the if/else.
2402 bool CondConstant;
2403 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002404 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002405 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002406 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002407 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002408 return;
2409 }
2410
2411 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2412 // emit the conditional branch.
2413 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2414 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2415 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2416 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2417
2418 // Emit the 'then' code.
2419 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002420 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002421 CGF.EmitBranch(ContBlock);
2422 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002423 // There is no need to emit line number for unconditional branch.
2424 (void)ApplyDebugLocation::CreateEmpty(CGF);
2425 CGF.EmitBlock(ElseBlock);
2426 ElseGen(CGF);
2427 // There is no need to emit line number for unconditional branch.
2428 (void)ApplyDebugLocation::CreateEmpty(CGF);
2429 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002430 // Emit the continuation block for code after the if.
2431 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002432}
2433
Alexey Bataev1d677132015-04-22 13:57:31 +00002434void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2435 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002436 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002437 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002438 if (!CGF.HaveInsertPoint())
2439 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002440 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002441 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2442 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002443 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002444 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002445 llvm::Value *Args[] = {
2446 RTLoc,
2447 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002448 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002449 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2450 RealArgs.append(std::begin(Args), std::end(Args));
2451 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2452
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002453 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002454 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2455 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002456 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2457 PrePostActionTy &) {
2458 auto &RT = CGF.CGM.getOpenMPRuntime();
2459 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002460 // Build calls:
2461 // __kmpc_serialized_parallel(&Loc, GTid);
2462 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002463 CGF.EmitRuntimeCall(
2464 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002465
Alexey Bataev1d677132015-04-22 13:57:31 +00002466 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002467 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002468 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002469 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2470 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002471 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002472 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2473 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2474 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2475 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002476 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002477
Alexey Bataev1d677132015-04-22 13:57:31 +00002478 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002479 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002480 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002481 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2482 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002483 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002484 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002485 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002486 else {
2487 RegionCodeGenTy ThenRCG(ThenGen);
2488 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002489 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002490}
2491
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002492// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002493// thread-ID variable (it is passed in a first argument of the outlined function
2494// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2495// regular serial code region, get thread ID by calling kmp_int32
2496// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2497// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002498Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2499 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002500 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002501 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002502 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002503 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002504
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002505 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002506 auto Int32Ty =
2507 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2508 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2509 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002510 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002511
2512 return ThreadIDTemp;
2513}
2514
Alexey Bataev97720002014-11-11 04:05:39 +00002515llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002516CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002517 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002518 SmallString<256> Buffer;
2519 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002520 Out << Name;
2521 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002522 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2523 if (Elem.second) {
2524 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002525 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002526 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002527 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002528
David Blaikie13156b62014-11-19 03:06:06 +00002529 return Elem.second = new llvm::GlobalVariable(
2530 CGM.getModule(), Ty, /*IsConstant*/ false,
2531 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2532 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002533}
2534
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002535llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002536 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002537 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002538}
2539
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002540namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002541/// Common pre(post)-action for different OpenMP constructs.
2542class CommonActionTy final : public PrePostActionTy {
2543 llvm::Value *EnterCallee;
2544 ArrayRef<llvm::Value *> EnterArgs;
2545 llvm::Value *ExitCallee;
2546 ArrayRef<llvm::Value *> ExitArgs;
2547 bool Conditional;
2548 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002549
2550public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002551 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2552 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2553 bool Conditional = false)
2554 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2555 ExitArgs(ExitArgs), Conditional(Conditional) {}
2556 void Enter(CodeGenFunction &CGF) override {
2557 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2558 if (Conditional) {
2559 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2560 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2561 ContBlock = CGF.createBasicBlock("omp_if.end");
2562 // Generate the branch (If-stmt)
2563 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2564 CGF.EmitBlock(ThenBlock);
2565 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002566 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002567 void Done(CodeGenFunction &CGF) {
2568 // Emit the rest of blocks/branches
2569 CGF.EmitBranch(ContBlock);
2570 CGF.EmitBlock(ContBlock, true);
2571 }
2572 void Exit(CodeGenFunction &CGF) override {
2573 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002574 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002575};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002576} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002577
2578void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2579 StringRef CriticalName,
2580 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002581 SourceLocation Loc, const Expr *Hint) {
2582 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002583 // CriticalOpGen();
2584 // __kmpc_end_critical(ident_t *, gtid, Lock);
2585 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002586 if (!CGF.HaveInsertPoint())
2587 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002588 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2589 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002590 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2591 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002592 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002593 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2594 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2595 }
2596 CommonActionTy Action(
2597 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2598 : OMPRTL__kmpc_critical),
2599 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2600 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002601 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002602}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002603
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002604void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002605 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002606 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002607 if (!CGF.HaveInsertPoint())
2608 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002609 // if(__kmpc_master(ident_t *, gtid)) {
2610 // MasterOpGen();
2611 // __kmpc_end_master(ident_t *, gtid);
2612 // }
2613 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002614 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002615 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2616 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2617 /*Conditional=*/true);
2618 MasterOpGen.setAction(Action);
2619 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2620 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002621}
2622
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002623void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2624 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002625 if (!CGF.HaveInsertPoint())
2626 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002627 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2628 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002629 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002630 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002631 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002632 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2633 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002634}
2635
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002636void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2637 const RegionCodeGenTy &TaskgroupOpGen,
2638 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002639 if (!CGF.HaveInsertPoint())
2640 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002641 // __kmpc_taskgroup(ident_t *, gtid);
2642 // TaskgroupOpGen();
2643 // __kmpc_end_taskgroup(ident_t *, gtid);
2644 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002645 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2646 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2647 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2648 Args);
2649 TaskgroupOpGen.setAction(Action);
2650 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002651}
2652
John McCall7f416cc2015-09-08 08:05:57 +00002653/// Given an array of pointers to variables, project the address of a
2654/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002655static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2656 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002657 // Pull out the pointer to the variable.
2658 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002659 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002660 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2661
2662 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002663 Addr = CGF.Builder.CreateElementBitCast(
2664 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002665 return Addr;
2666}
2667
Alexey Bataeva63048e2015-03-23 06:18:07 +00002668static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002669 CodeGenModule &CGM, llvm::Type *ArgsType,
2670 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2671 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002672 auto &C = CGM.getContext();
2673 // void copy_func(void *LHSArg, void *RHSArg);
2674 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002675 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2676 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002677 Args.push_back(&LHSArg);
2678 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002679 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002680 auto *Fn = llvm::Function::Create(
2681 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2682 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002683 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002684 CodeGenFunction CGF(CGM);
2685 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002686 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002687 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002688 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2689 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2690 ArgsType), CGF.getPointerAlign());
2691 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2692 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2693 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002694 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2695 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2696 // ...
2697 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002698 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002699 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2700 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2701
2702 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2703 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2704
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002705 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2706 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002707 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002708 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002709 CGF.FinishFunction();
2710 return Fn;
2711}
2712
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002713void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002714 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002715 SourceLocation Loc,
2716 ArrayRef<const Expr *> CopyprivateVars,
2717 ArrayRef<const Expr *> SrcExprs,
2718 ArrayRef<const Expr *> DstExprs,
2719 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002720 if (!CGF.HaveInsertPoint())
2721 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002722 assert(CopyprivateVars.size() == SrcExprs.size() &&
2723 CopyprivateVars.size() == DstExprs.size() &&
2724 CopyprivateVars.size() == AssignmentOps.size());
2725 auto &C = CGM.getContext();
2726 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002727 // if(__kmpc_single(ident_t *, gtid)) {
2728 // SingleOpGen();
2729 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002730 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002731 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002732 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2733 // <copy_func>, did_it);
2734
John McCall7f416cc2015-09-08 08:05:57 +00002735 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002736 if (!CopyprivateVars.empty()) {
2737 // int32 did_it = 0;
2738 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2739 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002740 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002741 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002742 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002743 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002744 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2745 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2746 /*Conditional=*/true);
2747 SingleOpGen.setAction(Action);
2748 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2749 if (DidIt.isValid()) {
2750 // did_it = 1;
2751 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2752 }
2753 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002754 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2755 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002756 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002757 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2758 auto CopyprivateArrayTy =
2759 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2760 /*IndexTypeQuals=*/0);
2761 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002762 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002763 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2764 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002765 Address Elem = CGF.Builder.CreateConstArrayGEP(
2766 CopyprivateList, I, CGF.getPointerSize());
2767 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002768 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002769 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2770 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002771 }
2772 // Build function that copies private values from single region to all other
2773 // threads in the corresponding parallel region.
2774 auto *CpyFn = emitCopyprivateCopyFunction(
2775 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002776 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002777 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002778 Address CL =
2779 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2780 CGF.VoidPtrTy);
2781 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002782 llvm::Value *Args[] = {
2783 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2784 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002785 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002786 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002787 CpyFn, // void (*) (void *, void *) <copy_func>
2788 DidItVal // i32 did_it
2789 };
2790 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2791 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002792}
2793
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002794void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2795 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002796 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002797 if (!CGF.HaveInsertPoint())
2798 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002799 // __kmpc_ordered(ident_t *, gtid);
2800 // OrderedOpGen();
2801 // __kmpc_end_ordered(ident_t *, gtid);
2802 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002803 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002804 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002805 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2806 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2807 Args);
2808 OrderedOpGen.setAction(Action);
2809 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2810 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002811 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002812 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002813}
2814
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002815void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002816 OpenMPDirectiveKind Kind, bool EmitChecks,
2817 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002818 if (!CGF.HaveInsertPoint())
2819 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002820 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002821 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002822 unsigned Flags;
2823 if (Kind == OMPD_for)
2824 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2825 else if (Kind == OMPD_sections)
2826 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2827 else if (Kind == OMPD_single)
2828 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2829 else if (Kind == OMPD_barrier)
2830 Flags = OMP_IDENT_BARRIER_EXPL;
2831 else
2832 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002833 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2834 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002835 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2836 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002837 if (auto *OMPRegionInfo =
2838 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002839 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002840 auto *Result = CGF.EmitRuntimeCall(
2841 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002842 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002843 // if (__kmpc_cancel_barrier()) {
2844 // exit from construct;
2845 // }
2846 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2847 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2848 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2849 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2850 CGF.EmitBlock(ExitBB);
2851 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002852 auto CancelDestination =
2853 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002854 CGF.EmitBranchThroughCleanup(CancelDestination);
2855 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2856 }
2857 return;
2858 }
2859 }
2860 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002861}
2862
Alexander Musmanc6388682014-12-15 07:07:06 +00002863/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2864static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002865 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002866 switch (ScheduleKind) {
2867 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002868 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2869 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002870 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002871 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002872 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002873 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002874 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002875 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2876 case OMPC_SCHEDULE_auto:
2877 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002878 case OMPC_SCHEDULE_unknown:
2879 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002880 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002881 }
2882 llvm_unreachable("Unexpected runtime schedule");
2883}
2884
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002885/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2886static OpenMPSchedType
2887getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2888 // only static is allowed for dist_schedule
2889 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2890}
2891
Alexander Musmanc6388682014-12-15 07:07:06 +00002892bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2893 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002894 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002895 return Schedule == OMP_sch_static;
2896}
2897
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002898bool CGOpenMPRuntime::isStaticNonchunked(
2899 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2900 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2901 return Schedule == OMP_dist_sch_static;
2902}
2903
2904
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002905bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002906 auto Schedule =
2907 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002908 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2909 return Schedule != OMP_sch_static;
2910}
2911
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002912static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2913 OpenMPScheduleClauseModifier M1,
2914 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002915 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002916 switch (M1) {
2917 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002918 Modifier = OMP_sch_modifier_monotonic;
2919 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002920 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002921 Modifier = OMP_sch_modifier_nonmonotonic;
2922 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002923 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002924 if (Schedule == OMP_sch_static_chunked)
2925 Schedule = OMP_sch_static_balanced_chunked;
2926 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002927 case OMPC_SCHEDULE_MODIFIER_last:
2928 case OMPC_SCHEDULE_MODIFIER_unknown:
2929 break;
2930 }
2931 switch (M2) {
2932 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002933 Modifier = OMP_sch_modifier_monotonic;
2934 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002935 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002936 Modifier = OMP_sch_modifier_nonmonotonic;
2937 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002938 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002939 if (Schedule == OMP_sch_static_chunked)
2940 Schedule = OMP_sch_static_balanced_chunked;
2941 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002942 case OMPC_SCHEDULE_MODIFIER_last:
2943 case OMPC_SCHEDULE_MODIFIER_unknown:
2944 break;
2945 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002946 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002947}
2948
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002949void CGOpenMPRuntime::emitForDispatchInit(
2950 CodeGenFunction &CGF, SourceLocation Loc,
2951 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2952 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002953 if (!CGF.HaveInsertPoint())
2954 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002955 OpenMPSchedType Schedule = getRuntimeSchedule(
2956 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002957 assert(Ordered ||
2958 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002959 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2960 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002961 // Call __kmpc_dispatch_init(
2962 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2963 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2964 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002965
John McCall7f416cc2015-09-08 08:05:57 +00002966 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002967 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2968 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002969 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002970 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2971 CGF.Builder.getInt32(addMonoNonMonoModifier(
2972 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002973 DispatchValues.LB, // Lower
2974 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002975 CGF.Builder.getIntN(IVSize, 1), // Stride
2976 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002977 };
2978 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2979}
2980
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002981static void emitForStaticInitCall(
2982 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2983 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2984 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002985 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002986 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002987 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002988
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002989 assert(!Values.Ordered);
2990 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2991 Schedule == OMP_sch_static_balanced_chunked ||
2992 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2993 Schedule == OMP_dist_sch_static ||
2994 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002995
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002996 // Call __kmpc_for_static_init(
2997 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2998 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2999 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3000 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3001 llvm::Value *Chunk = Values.Chunk;
3002 if (Chunk == nullptr) {
3003 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3004 Schedule == OMP_dist_sch_static) &&
3005 "expected static non-chunked schedule");
3006 // If the Chunk was not specified in the clause - use default value 1.
3007 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3008 } else {
3009 assert((Schedule == OMP_sch_static_chunked ||
3010 Schedule == OMP_sch_static_balanced_chunked ||
3011 Schedule == OMP_ord_static_chunked ||
3012 Schedule == OMP_dist_sch_static_chunked) &&
3013 "expected static chunked schedule");
3014 }
3015 llvm::Value *Args[] = {
3016 UpdateLocation,
3017 ThreadId,
3018 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3019 M2)), // Schedule type
3020 Values.IL.getPointer(), // &isLastIter
3021 Values.LB.getPointer(), // &LB
3022 Values.UB.getPointer(), // &UB
3023 Values.ST.getPointer(), // &Stride
3024 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3025 Chunk // Chunk
3026 };
3027 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003028}
3029
John McCall7f416cc2015-09-08 08:05:57 +00003030void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3031 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003032 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003033 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003034 const StaticRTInput &Values) {
3035 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3036 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3037 assert(isOpenMPWorksharingDirective(DKind) &&
3038 "Expected loop-based or sections-based directive.");
3039 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3040 isOpenMPLoopDirective(DKind)
3041 ? OMP_IDENT_WORK_LOOP
3042 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003043 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003044 auto *StaticInitFunction =
3045 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003046 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003047 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003048}
John McCall7f416cc2015-09-08 08:05:57 +00003049
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003050void CGOpenMPRuntime::emitDistributeStaticInit(
3051 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003052 OpenMPDistScheduleClauseKind SchedKind,
3053 const CGOpenMPRuntime::StaticRTInput &Values) {
3054 OpenMPSchedType ScheduleNum =
3055 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3056 auto *UpdatedLocation =
3057 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003058 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003059 auto *StaticInitFunction =
3060 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003061 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3062 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003063 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003064}
3065
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003066void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003067 SourceLocation Loc,
3068 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003069 if (!CGF.HaveInsertPoint())
3070 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003071 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003072 llvm::Value *Args[] = {
3073 emitUpdateLocation(CGF, Loc,
3074 isOpenMPDistributeDirective(DKind)
3075 ? OMP_IDENT_WORK_DISTRIBUTE
3076 : isOpenMPLoopDirective(DKind)
3077 ? OMP_IDENT_WORK_LOOP
3078 : OMP_IDENT_WORK_SECTIONS),
3079 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003080 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3081 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003082}
3083
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003084void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3085 SourceLocation Loc,
3086 unsigned IVSize,
3087 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003088 if (!CGF.HaveInsertPoint())
3089 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003090 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003091 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003092 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3093}
3094
Alexander Musman92bdaab2015-03-12 13:37:50 +00003095llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3096 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003097 bool IVSigned, Address IL,
3098 Address LB, Address UB,
3099 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003100 // Call __kmpc_dispatch_next(
3101 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3102 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3103 // kmp_int[32|64] *p_stride);
3104 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003105 emitUpdateLocation(CGF, Loc),
3106 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003107 IL.getPointer(), // &isLastIter
3108 LB.getPointer(), // &Lower
3109 UB.getPointer(), // &Upper
3110 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003111 };
3112 llvm::Value *Call =
3113 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3114 return CGF.EmitScalarConversion(
3115 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003116 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003117}
3118
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003119void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3120 llvm::Value *NumThreads,
3121 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003122 if (!CGF.HaveInsertPoint())
3123 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003124 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3125 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003126 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003127 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003128 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3129 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003130}
3131
Alexey Bataev7f210c62015-06-18 13:40:03 +00003132void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3133 OpenMPProcBindClauseKind ProcBind,
3134 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003135 if (!CGF.HaveInsertPoint())
3136 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003137 // Constants for proc bind value accepted by the runtime.
3138 enum ProcBindTy {
3139 ProcBindFalse = 0,
3140 ProcBindTrue,
3141 ProcBindMaster,
3142 ProcBindClose,
3143 ProcBindSpread,
3144 ProcBindIntel,
3145 ProcBindDefault
3146 } RuntimeProcBind;
3147 switch (ProcBind) {
3148 case OMPC_PROC_BIND_master:
3149 RuntimeProcBind = ProcBindMaster;
3150 break;
3151 case OMPC_PROC_BIND_close:
3152 RuntimeProcBind = ProcBindClose;
3153 break;
3154 case OMPC_PROC_BIND_spread:
3155 RuntimeProcBind = ProcBindSpread;
3156 break;
3157 case OMPC_PROC_BIND_unknown:
3158 llvm_unreachable("Unsupported proc_bind value.");
3159 }
3160 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3161 llvm::Value *Args[] = {
3162 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3163 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3164 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3165}
3166
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003167void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3168 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003169 if (!CGF.HaveInsertPoint())
3170 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003171 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003172 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3173 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003174}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003175
Alexey Bataev62b63b12015-03-10 07:28:44 +00003176namespace {
3177/// \brief Indexes of fields for type kmp_task_t.
3178enum KmpTaskTFields {
3179 /// \brief List of shared variables.
3180 KmpTaskTShareds,
3181 /// \brief Task routine.
3182 KmpTaskTRoutine,
3183 /// \brief Partition id for the untied tasks.
3184 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003185 /// Function with call of destructors for private variables.
3186 Data1,
3187 /// Task priority.
3188 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003189 /// (Taskloops only) Lower bound.
3190 KmpTaskTLowerBound,
3191 /// (Taskloops only) Upper bound.
3192 KmpTaskTUpperBound,
3193 /// (Taskloops only) Stride.
3194 KmpTaskTStride,
3195 /// (Taskloops only) Is last iteration flag.
3196 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003197 /// (Taskloops only) Reduction data.
3198 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003199};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003200} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003201
Samuel Antaoee8fb302016-01-06 13:42:12 +00003202bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3203 // FIXME: Add other entries type when they become supported.
3204 return OffloadEntriesTargetRegion.empty();
3205}
3206
3207/// \brief Initialize target region entry.
3208void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3209 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3210 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003211 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003212 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3213 "only required for the device "
3214 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003215 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003216 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3217 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003218 ++OffloadingEntriesNum;
3219}
3220
3221void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3222 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3223 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003224 llvm::Constant *Addr, llvm::Constant *ID,
3225 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003226 // If we are emitting code for a target, the entry is already initialized,
3227 // only has to be registered.
3228 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003229 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003230 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003231 auto &Entry =
3232 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003233 assert(Entry.isValid() && "Entry not initialized!");
3234 Entry.setAddress(Addr);
3235 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003236 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003237 return;
3238 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003239 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003240 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003241 }
3242}
3243
3244bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003245 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3246 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003247 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3248 if (PerDevice == OffloadEntriesTargetRegion.end())
3249 return false;
3250 auto PerFile = PerDevice->second.find(FileID);
3251 if (PerFile == PerDevice->second.end())
3252 return false;
3253 auto PerParentName = PerFile->second.find(ParentName);
3254 if (PerParentName == PerFile->second.end())
3255 return false;
3256 auto PerLine = PerParentName->second.find(LineNum);
3257 if (PerLine == PerParentName->second.end())
3258 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003259 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003260 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003261 return false;
3262 return true;
3263}
3264
3265void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3266 const OffloadTargetRegionEntryInfoActTy &Action) {
3267 // Scan all target region entries and perform the provided action.
3268 for (auto &D : OffloadEntriesTargetRegion)
3269 for (auto &F : D.second)
3270 for (auto &P : F.second)
3271 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003272 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003273}
3274
3275/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3276/// \a Codegen. This is used to emit the two functions that register and
3277/// unregister the descriptor of the current compilation unit.
3278static llvm::Function *
3279createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3280 const RegionCodeGenTy &Codegen) {
3281 auto &C = CGM.getContext();
3282 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003283 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003284 Args.push_back(&DummyPtr);
3285
3286 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003287 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003288 auto FTy = CGM.getTypes().GetFunctionType(FI);
3289 auto *Fn =
3290 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3291 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3292 Codegen(CGF);
3293 CGF.FinishFunction();
3294 return Fn;
3295}
3296
3297llvm::Function *
3298CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3299
3300 // If we don't have entries or if we are emitting code for the device, we
3301 // don't need to do anything.
3302 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3303 return nullptr;
3304
3305 auto &M = CGM.getModule();
3306 auto &C = CGM.getContext();
3307
3308 // Get list of devices we care about
3309 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3310
3311 // We should be creating an offloading descriptor only if there are devices
3312 // specified.
3313 assert(!Devices.empty() && "No OpenMP offloading devices??");
3314
3315 // Create the external variables that will point to the begin and end of the
3316 // host entries section. These will be defined by the linker.
3317 auto *OffloadEntryTy =
3318 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3319 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3320 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003321 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003322 ".omp_offloading.entries_begin");
3323 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3324 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003325 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003326 ".omp_offloading.entries_end");
3327
3328 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003329 auto *DeviceImageTy = cast<llvm::StructType>(
3330 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003331 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003332 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003333
3334 for (unsigned i = 0; i < Devices.size(); ++i) {
3335 StringRef T = Devices[i].getTriple();
3336 auto *ImgBegin = new llvm::GlobalVariable(
3337 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003338 /*Initializer=*/nullptr,
3339 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003340 auto *ImgEnd = new llvm::GlobalVariable(
3341 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003342 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003343
John McCall6c9f1fdb2016-11-19 08:17:24 +00003344 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3345 Dev.add(ImgBegin);
3346 Dev.add(ImgEnd);
3347 Dev.add(HostEntriesBegin);
3348 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003349 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003350 }
3351
3352 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003353 llvm::GlobalVariable *DeviceImages =
3354 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3355 CGM.getPointerAlign(),
3356 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003357 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003358
3359 // This is a Zero array to be used in the creation of the constant expressions
3360 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3361 llvm::Constant::getNullValue(CGM.Int32Ty)};
3362
3363 // Create the target region descriptor.
3364 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3365 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003366 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003367 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3368 DescInit.addInt(CGM.Int32Ty, Devices.size());
3369 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3370 DeviceImages,
3371 Index));
3372 DescInit.add(HostEntriesBegin);
3373 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003374
John McCall6c9f1fdb2016-11-19 08:17:24 +00003375 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3376 CGM.getPointerAlign(),
3377 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003378
3379 // Emit code to register or unregister the descriptor at execution
3380 // startup or closing, respectively.
3381
3382 // Create a variable to drive the registration and unregistration of the
3383 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3384 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3385 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003386 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003387
3388 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003389 CGM, ".omp_offloading.descriptor_unreg",
3390 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003391 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3392 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003393 });
3394 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003395 CGM, ".omp_offloading.descriptor_reg",
3396 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003397 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3398 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003399 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3400 });
George Rokos29d0f002017-05-27 03:03:13 +00003401 if (CGM.supportsCOMDAT()) {
3402 // It is sufficient to call registration function only once, so create a
3403 // COMDAT group for registration/unregistration functions and associated
3404 // data. That would reduce startup time and code size. Registration
3405 // function serves as a COMDAT group key.
3406 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3407 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3408 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3409 RegFn->setComdat(ComdatKey);
3410 UnRegFn->setComdat(ComdatKey);
3411 DeviceImages->setComdat(ComdatKey);
3412 Desc->setComdat(ComdatKey);
3413 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003414 return RegFn;
3415}
3416
Samuel Antao2de62b02016-02-13 23:35:10 +00003417void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003418 llvm::Constant *Addr, uint64_t Size,
3419 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003420 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003421 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3422 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3423 llvm::LLVMContext &C = CGM.getModule().getContext();
3424 llvm::Module &M = CGM.getModule();
3425
3426 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003427 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003428
3429 // Create constant string with the name.
3430 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3431
3432 llvm::GlobalVariable *Str =
3433 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3434 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3435 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003436 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003437 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3438
John McCall6c9f1fdb2016-11-19 08:17:24 +00003439 // We can't have any padding between symbols, so we need to have 1-byte
3440 // alignment.
3441 auto Align = CharUnits::fromQuantity(1);
3442
Samuel Antaoee8fb302016-01-06 13:42:12 +00003443 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003444 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003445 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3446 EntryInit.add(AddrPtr);
3447 EntryInit.add(StrPtr);
3448 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003449 EntryInit.addInt(CGM.Int32Ty, Flags);
3450 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003451 llvm::GlobalVariable *Entry =
3452 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3453 Align,
3454 /*constant*/ true,
3455 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003456
3457 // The entry has to be created in the section the linker expects it to be.
3458 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003459}
3460
3461void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3462 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003463 // can easily figure out what to emit. The produced metadata looks like
3464 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003465 //
3466 // !omp_offload.info = !{!1, ...}
3467 //
3468 // Right now we only generate metadata for function that contain target
3469 // regions.
3470
3471 // If we do not have entries, we dont need to do anything.
3472 if (OffloadEntriesInfoManager.empty())
3473 return;
3474
3475 llvm::Module &M = CGM.getModule();
3476 llvm::LLVMContext &C = M.getContext();
3477 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3478 OrderedEntries(OffloadEntriesInfoManager.size());
3479
3480 // Create the offloading info metadata node.
3481 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3482
Simon Pilgrim2c518802017-03-30 14:13:19 +00003483 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003484 auto getMDInt = [&](unsigned v) {
3485 return llvm::ConstantAsMetadata::get(
3486 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3487 };
3488
3489 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3490
3491 // Create function that emits metadata for each target region entry;
3492 auto &&TargetRegionMetadataEmitter = [&](
3493 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003494 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3495 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3496 // Generate metadata for target regions. Each entry of this metadata
3497 // contains:
3498 // - Entry 0 -> Kind of this type of metadata (0).
3499 // - Entry 1 -> Device ID of the file where the entry was identified.
3500 // - Entry 2 -> File ID of the file where the entry was identified.
3501 // - Entry 3 -> Mangled name of the function where the entry was identified.
3502 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003503 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003504 // The first element of the metadata node is the kind.
3505 Ops.push_back(getMDInt(E.getKind()));
3506 Ops.push_back(getMDInt(DeviceID));
3507 Ops.push_back(getMDInt(FileID));
3508 Ops.push_back(getMDString(ParentName));
3509 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003510 Ops.push_back(getMDInt(E.getOrder()));
3511
3512 // Save this entry in the right position of the ordered entries array.
3513 OrderedEntries[E.getOrder()] = &E;
3514
3515 // Add metadata to the named metadata node.
3516 MD->addOperand(llvm::MDNode::get(C, Ops));
3517 };
3518
3519 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3520 TargetRegionMetadataEmitter);
3521
3522 for (auto *E : OrderedEntries) {
3523 assert(E && "All ordered entries must exist!");
3524 if (auto *CE =
3525 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3526 E)) {
3527 assert(CE->getID() && CE->getAddress() &&
3528 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003529 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003530 } else
3531 llvm_unreachable("Unsupported entry kind.");
3532 }
3533}
3534
3535/// \brief Loads all the offload entries information from the host IR
3536/// metadata.
3537void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3538 // If we are in target mode, load the metadata from the host IR. This code has
3539 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3540
3541 if (!CGM.getLangOpts().OpenMPIsDevice)
3542 return;
3543
3544 if (CGM.getLangOpts().OMPHostIRFile.empty())
3545 return;
3546
3547 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3548 if (Buf.getError())
3549 return;
3550
3551 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003552 auto ME = expectedToErrorOrAndEmitErrors(
3553 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003554
3555 if (ME.getError())
3556 return;
3557
3558 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3559 if (!MD)
3560 return;
3561
3562 for (auto I : MD->operands()) {
3563 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3564
3565 auto getMDInt = [&](unsigned Idx) {
3566 llvm::ConstantAsMetadata *V =
3567 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3568 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3569 };
3570
3571 auto getMDString = [&](unsigned Idx) {
3572 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3573 return V->getString();
3574 };
3575
3576 switch (getMDInt(0)) {
3577 default:
3578 llvm_unreachable("Unexpected metadata!");
3579 break;
3580 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3581 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3582 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3583 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3584 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003585 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003586 break;
3587 }
3588 }
3589}
3590
Alexey Bataev62b63b12015-03-10 07:28:44 +00003591void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3592 if (!KmpRoutineEntryPtrTy) {
3593 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3594 auto &C = CGM.getContext();
3595 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3596 FunctionProtoType::ExtProtoInfo EPI;
3597 KmpRoutineEntryPtrQTy = C.getPointerType(
3598 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3599 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3600 }
3601}
3602
Alexey Bataevc71a4092015-09-11 10:29:41 +00003603static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3604 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003605 auto *Field = FieldDecl::Create(
3606 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3607 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3608 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3609 Field->setAccess(AS_public);
3610 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003611 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003612}
3613
Samuel Antaoee8fb302016-01-06 13:42:12 +00003614QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3615
3616 // Make sure the type of the entry is already created. This is the type we
3617 // have to create:
3618 // struct __tgt_offload_entry{
3619 // void *addr; // Pointer to the offload entry info.
3620 // // (function or global)
3621 // char *name; // Name of the function or global.
3622 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003623 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3624 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003625 // };
3626 if (TgtOffloadEntryQTy.isNull()) {
3627 ASTContext &C = CGM.getContext();
3628 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3629 RD->startDefinition();
3630 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3631 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3632 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003633 addFieldToRecordDecl(
3634 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3635 addFieldToRecordDecl(
3636 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003637 RD->completeDefinition();
3638 TgtOffloadEntryQTy = C.getRecordType(RD);
3639 }
3640 return TgtOffloadEntryQTy;
3641}
3642
3643QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3644 // These are the types we need to build:
3645 // struct __tgt_device_image{
3646 // void *ImageStart; // Pointer to the target code start.
3647 // void *ImageEnd; // Pointer to the target code end.
3648 // // We also add the host entries to the device image, as it may be useful
3649 // // for the target runtime to have access to that information.
3650 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3651 // // the entries.
3652 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3653 // // entries (non inclusive).
3654 // };
3655 if (TgtDeviceImageQTy.isNull()) {
3656 ASTContext &C = CGM.getContext();
3657 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3658 RD->startDefinition();
3659 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3660 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3661 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3662 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3663 RD->completeDefinition();
3664 TgtDeviceImageQTy = C.getRecordType(RD);
3665 }
3666 return TgtDeviceImageQTy;
3667}
3668
3669QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3670 // struct __tgt_bin_desc{
3671 // int32_t NumDevices; // Number of devices supported.
3672 // __tgt_device_image *DeviceImages; // Arrays of device images
3673 // // (one per device).
3674 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3675 // // entries.
3676 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3677 // // entries (non inclusive).
3678 // };
3679 if (TgtBinaryDescriptorQTy.isNull()) {
3680 ASTContext &C = CGM.getContext();
3681 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3682 RD->startDefinition();
3683 addFieldToRecordDecl(
3684 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3685 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3686 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3687 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3688 RD->completeDefinition();
3689 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3690 }
3691 return TgtBinaryDescriptorQTy;
3692}
3693
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003694namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003695struct PrivateHelpersTy {
3696 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3697 const VarDecl *PrivateElemInit)
3698 : Original(Original), PrivateCopy(PrivateCopy),
3699 PrivateElemInit(PrivateElemInit) {}
3700 const VarDecl *Original;
3701 const VarDecl *PrivateCopy;
3702 const VarDecl *PrivateElemInit;
3703};
3704typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003705} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003706
Alexey Bataev9e034042015-05-05 04:05:12 +00003707static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003708createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003709 if (!Privates.empty()) {
3710 auto &C = CGM.getContext();
3711 // Build struct .kmp_privates_t. {
3712 // /* private vars */
3713 // };
3714 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3715 RD->startDefinition();
3716 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003717 auto *VD = Pair.second.Original;
3718 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003719 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003720 auto *FD = addFieldToRecordDecl(C, RD, Type);
3721 if (VD->hasAttrs()) {
3722 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3723 E(VD->getAttrs().end());
3724 I != E; ++I)
3725 FD->addAttr(*I);
3726 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003727 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003728 RD->completeDefinition();
3729 return RD;
3730 }
3731 return nullptr;
3732}
3733
Alexey Bataev9e034042015-05-05 04:05:12 +00003734static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003735createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3736 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003737 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003738 auto &C = CGM.getContext();
3739 // Build struct kmp_task_t {
3740 // void * shareds;
3741 // kmp_routine_entry_t routine;
3742 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003743 // kmp_cmplrdata_t data1;
3744 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003745 // For taskloops additional fields:
3746 // kmp_uint64 lb;
3747 // kmp_uint64 ub;
3748 // kmp_int64 st;
3749 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003750 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003751 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003752 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3753 UD->startDefinition();
3754 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3755 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3756 UD->completeDefinition();
3757 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003758 auto *RD = C.buildImplicitRecord("kmp_task_t");
3759 RD->startDefinition();
3760 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3761 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3762 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003763 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3764 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003765 if (isOpenMPTaskLoopDirective(Kind)) {
3766 QualType KmpUInt64Ty =
3767 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3768 QualType KmpInt64Ty =
3769 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3770 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3771 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3772 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3773 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003774 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003775 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003776 RD->completeDefinition();
3777 return RD;
3778}
3779
3780static RecordDecl *
3781createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003782 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003783 auto &C = CGM.getContext();
3784 // Build struct kmp_task_t_with_privates {
3785 // kmp_task_t task_data;
3786 // .kmp_privates_t. privates;
3787 // };
3788 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3789 RD->startDefinition();
3790 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003791 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3792 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3793 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003794 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003795 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003796}
3797
3798/// \brief Emit a proxy function which accepts kmp_task_t as the second
3799/// argument.
3800/// \code
3801/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003802/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003803/// For taskloops:
3804/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003805/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003806/// return 0;
3807/// }
3808/// \endcode
3809static llvm::Value *
3810emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003811 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3812 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003813 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003814 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3815 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003816 auto &C = CGM.getContext();
3817 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003818 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3819 ImplicitParamDecl::Other);
3820 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3821 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3822 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003823 Args.push_back(&GtidArg);
3824 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003825 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003826 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003827 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3828 auto *TaskEntry =
3829 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3830 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003831 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003832 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003833 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3834
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003835 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003836 // tt,
3837 // For taskloops:
3838 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3839 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003840 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003841 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003842 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3843 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3844 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003845 auto *KmpTaskTWithPrivatesQTyRD =
3846 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003847 LValue Base =
3848 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003849 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3850 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3851 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003852 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003853
3854 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3855 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003856 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003857 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003858 CGF.ConvertTypeForMem(SharedsPtrTy));
3859
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003860 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3861 llvm::Value *PrivatesParam;
3862 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3863 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3864 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003865 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003866 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003867 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003868
Alexey Bataev7292c292016-04-25 12:22:29 +00003869 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3870 TaskPrivatesMap,
3871 CGF.Builder
3872 .CreatePointerBitCastOrAddrSpaceCast(
3873 TDBase.getAddress(), CGF.VoidPtrTy)
3874 .getPointer()};
3875 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3876 std::end(CommonArgs));
3877 if (isOpenMPTaskLoopDirective(Kind)) {
3878 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3879 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3880 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3881 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3882 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3883 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3884 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3885 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3886 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3887 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3888 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3889 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003890 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3891 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3892 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003893 CallArgs.push_back(LBParam);
3894 CallArgs.push_back(UBParam);
3895 CallArgs.push_back(StParam);
3896 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003897 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003898 }
3899 CallArgs.push_back(SharedsParam);
3900
Alexey Bataev3c595a62017-08-14 15:01:03 +00003901 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3902 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003903 CGF.EmitStoreThroughLValue(
3904 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003905 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003906 CGF.FinishFunction();
3907 return TaskEntry;
3908}
3909
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003910static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3911 SourceLocation Loc,
3912 QualType KmpInt32Ty,
3913 QualType KmpTaskTWithPrivatesPtrQTy,
3914 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003915 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003916 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003917 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3918 ImplicitParamDecl::Other);
3919 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3920 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3921 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003922 Args.push_back(&GtidArg);
3923 Args.push_back(&TaskTypeArg);
3924 FunctionType::ExtInfo Info;
3925 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003926 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003927 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3928 auto *DestructorFn =
3929 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3930 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003931 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3932 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003933 CodeGenFunction CGF(CGM);
3934 CGF.disableDebugInfo();
3935 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3936 Args);
3937
Alexey Bataev31300ed2016-02-04 11:27:03 +00003938 LValue Base = CGF.EmitLoadOfPointerLValue(
3939 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3940 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003941 auto *KmpTaskTWithPrivatesQTyRD =
3942 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3943 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003944 Base = CGF.EmitLValueForField(Base, *FI);
3945 for (auto *Field :
3946 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3947 if (auto DtorKind = Field->getType().isDestructedType()) {
3948 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3949 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3950 }
3951 }
3952 CGF.FinishFunction();
3953 return DestructorFn;
3954}
3955
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003956/// \brief Emit a privates mapping function for correct handling of private and
3957/// firstprivate variables.
3958/// \code
3959/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3960/// **noalias priv1,..., <tyn> **noalias privn) {
3961/// *priv1 = &.privates.priv1;
3962/// ...;
3963/// *privn = &.privates.privn;
3964/// }
3965/// \endcode
3966static llvm::Value *
3967emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003968 ArrayRef<const Expr *> PrivateVars,
3969 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003970 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003971 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003972 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003973 auto &C = CGM.getContext();
3974 FunctionArgList Args;
3975 ImplicitParamDecl TaskPrivatesArg(
3976 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003977 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3978 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003979 Args.push_back(&TaskPrivatesArg);
3980 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3981 unsigned Counter = 1;
3982 for (auto *E: PrivateVars) {
3983 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003984 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3985 C.getPointerType(C.getPointerType(E->getType()))
3986 .withConst()
3987 .withRestrict(),
3988 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003989 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3990 PrivateVarsPos[VD] = Counter;
3991 ++Counter;
3992 }
3993 for (auto *E : FirstprivateVars) {
3994 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003995 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3996 C.getPointerType(C.getPointerType(E->getType()))
3997 .withConst()
3998 .withRestrict(),
3999 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004000 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4001 PrivateVarsPos[VD] = Counter;
4002 ++Counter;
4003 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004004 for (auto *E: LastprivateVars) {
4005 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004006 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4007 C.getPointerType(C.getPointerType(E->getType()))
4008 .withConst()
4009 .withRestrict(),
4010 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004011 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4012 PrivateVarsPos[VD] = Counter;
4013 ++Counter;
4014 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004015 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004016 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004017 auto *TaskPrivatesMapTy =
4018 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4019 auto *TaskPrivatesMap = llvm::Function::Create(
4020 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4021 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004022 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4023 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004024 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004025 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004026 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004027 CodeGenFunction CGF(CGM);
4028 CGF.disableDebugInfo();
4029 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4030 TaskPrivatesMapFnInfo, Args);
4031
4032 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004033 LValue Base = CGF.EmitLoadOfPointerLValue(
4034 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4035 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004036 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4037 Counter = 0;
4038 for (auto *Field : PrivatesQTyRD->fields()) {
4039 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4040 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004041 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004042 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4043 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004044 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004045 ++Counter;
4046 }
4047 CGF.FinishFunction();
4048 return TaskPrivatesMap;
4049}
4050
Alexey Bataev9e034042015-05-05 04:05:12 +00004051static int array_pod_sort_comparator(const PrivateDataTy *P1,
4052 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004053 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4054}
4055
Alexey Bataevf93095a2016-05-05 08:46:22 +00004056/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004057static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004058 const OMPExecutableDirective &D,
4059 Address KmpTaskSharedsPtr, LValue TDBase,
4060 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4061 QualType SharedsTy, QualType SharedsPtrTy,
4062 const OMPTaskDataTy &Data,
4063 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4064 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004065 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4066 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4067 LValue SrcBase;
4068 if (!Data.FirstprivateVars.empty()) {
4069 SrcBase = CGF.MakeAddrLValue(
4070 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4071 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4072 SharedsTy);
4073 }
4074 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4075 cast<CapturedStmt>(*D.getAssociatedStmt()));
4076 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4077 for (auto &&Pair : Privates) {
4078 auto *VD = Pair.second.PrivateCopy;
4079 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004080 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4081 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004082 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004083 if (auto *Elem = Pair.second.PrivateElemInit) {
4084 auto *OriginalVD = Pair.second.Original;
4085 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4086 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4087 SharedRefLValue = CGF.MakeAddrLValue(
4088 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004089 SharedRefLValue.getType(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004090 LValueBaseInfo(AlignmentSource::Decl),
4091 SharedRefLValue.getTBAAInfo());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004092 QualType Type = OriginalVD->getType();
4093 if (Type->isArrayType()) {
4094 // Initialize firstprivate array.
4095 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4096 // Perform simple memcpy.
4097 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4098 SharedRefLValue.getAddress(), Type);
4099 } else {
4100 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004101 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004102 CGF.EmitOMPAggregateAssign(
4103 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4104 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4105 Address SrcElement) {
4106 // Clean up any temporaries needed by the initialization.
4107 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4108 InitScope.addPrivate(
4109 Elem, [SrcElement]() -> Address { return SrcElement; });
4110 (void)InitScope.Privatize();
4111 // Emit initialization for single element.
4112 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4113 CGF, &CapturesInfo);
4114 CGF.EmitAnyExprToMem(Init, DestElement,
4115 Init->getType().getQualifiers(),
4116 /*IsInitializer=*/false);
4117 });
4118 }
4119 } else {
4120 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4121 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4122 return SharedRefLValue.getAddress();
4123 });
4124 (void)InitScope.Privatize();
4125 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4126 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4127 /*capturedByInit=*/false);
4128 }
4129 } else
4130 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4131 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004132 ++FI;
4133 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004134}
4135
4136/// Check if duplication function is required for taskloops.
4137static bool checkInitIsRequired(CodeGenFunction &CGF,
4138 ArrayRef<PrivateDataTy> Privates) {
4139 bool InitRequired = false;
4140 for (auto &&Pair : Privates) {
4141 auto *VD = Pair.second.PrivateCopy;
4142 auto *Init = VD->getAnyInitializer();
4143 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4144 !CGF.isTrivialInitializer(Init));
4145 }
4146 return InitRequired;
4147}
4148
4149
4150/// Emit task_dup function (for initialization of
4151/// private/firstprivate/lastprivate vars and last_iter flag)
4152/// \code
4153/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4154/// lastpriv) {
4155/// // setup lastprivate flag
4156/// task_dst->last = lastpriv;
4157/// // could be constructor calls here...
4158/// }
4159/// \endcode
4160static llvm::Value *
4161emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4162 const OMPExecutableDirective &D,
4163 QualType KmpTaskTWithPrivatesPtrQTy,
4164 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4165 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4166 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4167 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4168 auto &C = CGM.getContext();
4169 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004170 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4171 KmpTaskTWithPrivatesPtrQTy,
4172 ImplicitParamDecl::Other);
4173 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4174 KmpTaskTWithPrivatesPtrQTy,
4175 ImplicitParamDecl::Other);
4176 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4177 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004178 Args.push_back(&DstArg);
4179 Args.push_back(&SrcArg);
4180 Args.push_back(&LastprivArg);
4181 auto &TaskDupFnInfo =
4182 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4183 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4184 auto *TaskDup =
4185 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4186 ".omp_task_dup.", &CGM.getModule());
4187 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4188 CodeGenFunction CGF(CGM);
4189 CGF.disableDebugInfo();
4190 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4191
4192 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4193 CGF.GetAddrOfLocalVar(&DstArg),
4194 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4195 // task_dst->liter = lastpriv;
4196 if (WithLastIter) {
4197 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4198 LValue Base = CGF.EmitLValueForField(
4199 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4200 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4201 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4202 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4203 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4204 }
4205
4206 // Emit initial values for private copies (if any).
4207 assert(!Privates.empty());
4208 Address KmpTaskSharedsPtr = Address::invalid();
4209 if (!Data.FirstprivateVars.empty()) {
4210 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4211 CGF.GetAddrOfLocalVar(&SrcArg),
4212 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4213 LValue Base = CGF.EmitLValueForField(
4214 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4215 KmpTaskSharedsPtr = Address(
4216 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4217 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4218 KmpTaskTShareds)),
4219 Loc),
4220 CGF.getNaturalTypeAlignment(SharedsTy));
4221 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004222 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4223 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004224 CGF.FinishFunction();
4225 return TaskDup;
4226}
4227
Alexey Bataev8a831592016-05-10 10:36:51 +00004228/// Checks if destructor function is required to be generated.
4229/// \return true if cleanups are required, false otherwise.
4230static bool
4231checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4232 bool NeedsCleanup = false;
4233 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4234 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4235 for (auto *FD : PrivateRD->fields()) {
4236 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4237 if (NeedsCleanup)
4238 break;
4239 }
4240 return NeedsCleanup;
4241}
4242
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004243CGOpenMPRuntime::TaskResultTy
4244CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4245 const OMPExecutableDirective &D,
4246 llvm::Value *TaskFunction, QualType SharedsTy,
4247 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004248 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004249 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004250 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004251 auto I = Data.PrivateCopies.begin();
4252 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004253 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4254 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004255 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004256 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4257 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004258 ++I;
4259 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004260 I = Data.FirstprivateCopies.begin();
4261 auto IElemInitRef = Data.FirstprivateInits.begin();
4262 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004263 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4264 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004265 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004266 PrivateHelpersTy(
4267 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4268 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004269 ++I;
4270 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004271 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004272 I = Data.LastprivateCopies.begin();
4273 for (auto *E : Data.LastprivateVars) {
4274 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4275 Privates.push_back(std::make_pair(
4276 C.getDeclAlign(VD),
4277 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4278 /*PrivateElemInit=*/nullptr)));
4279 ++I;
4280 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004281 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4282 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004283 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4284 // Build type kmp_routine_entry_t (if not built yet).
4285 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004286 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004287 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4288 if (SavedKmpTaskloopTQTy.isNull()) {
4289 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4290 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4291 }
4292 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004293 } else {
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004294 assert(D.getDirectiveKind() == OMPD_task &&
4295 "Expected taskloop or task directive");
4296 if (SavedKmpTaskTQTy.isNull()) {
4297 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4298 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4299 }
4300 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004301 }
4302 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004303 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004304 auto *KmpTaskTWithPrivatesQTyRD =
4305 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4306 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4307 QualType KmpTaskTWithPrivatesPtrQTy =
4308 C.getPointerType(KmpTaskTWithPrivatesQTy);
4309 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4310 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004311 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004312 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4313
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004314 // Emit initial values for private copies (if any).
4315 llvm::Value *TaskPrivatesMap = nullptr;
4316 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004317 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004318 if (!Privates.empty()) {
4319 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004320 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4321 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4322 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004323 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4324 TaskPrivatesMap, TaskPrivatesMapTy);
4325 } else {
4326 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4327 cast<llvm::PointerType>(TaskPrivatesMapTy));
4328 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004329 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4330 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004331 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004332 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4333 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4334 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004335
4336 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4337 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4338 // kmp_routine_entry_t *task_entry);
4339 // Task flags. Format is taken from
4340 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4341 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004342 enum {
4343 TiedFlag = 0x1,
4344 FinalFlag = 0x2,
4345 DestructorsFlag = 0x8,
4346 PriorityFlag = 0x20
4347 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004348 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004349 bool NeedsCleanup = false;
4350 if (!Privates.empty()) {
4351 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4352 if (NeedsCleanup)
4353 Flags = Flags | DestructorsFlag;
4354 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004355 if (Data.Priority.getInt())
4356 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004357 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004358 Data.Final.getPointer()
4359 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004360 CGF.Builder.getInt32(FinalFlag),
4361 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004362 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004363 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004364 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004365 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4366 getThreadID(CGF, Loc), TaskFlags,
4367 KmpTaskTWithPrivatesTySize, SharedsSize,
4368 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4369 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004370 auto *NewTask = CGF.EmitRuntimeCall(
4371 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004372 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4373 NewTask, KmpTaskTWithPrivatesPtrTy);
4374 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4375 KmpTaskTWithPrivatesQTy);
4376 LValue TDBase =
4377 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004378 // Fill the data in the resulting kmp_task_t record.
4379 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004380 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004381 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004382 KmpTaskSharedsPtr =
4383 Address(CGF.EmitLoadOfScalar(
4384 CGF.EmitLValueForField(
4385 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4386 KmpTaskTShareds)),
4387 Loc),
4388 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004389 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004390 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004391 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004392 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004393 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004394 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4395 SharedsTy, SharedsPtrTy, Data, Privates,
4396 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004397 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4398 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4399 Result.TaskDupFn = emitTaskDupFunction(
4400 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4401 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4402 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004403 }
4404 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004405 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4406 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004407 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004408 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4409 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4410 if (NeedsCleanup) {
4411 llvm::Value *DestructorFn = emitDestructorsFunction(
4412 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4413 KmpTaskTWithPrivatesQTy);
4414 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4415 LValue DestructorsLV = CGF.EmitLValueForField(
4416 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4417 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4418 DestructorFn, KmpRoutineEntryPtrTy),
4419 DestructorsLV);
4420 }
4421 // Set priority.
4422 if (Data.Priority.getInt()) {
4423 LValue Data2LV = CGF.EmitLValueForField(
4424 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4425 LValue PriorityLV = CGF.EmitLValueForField(
4426 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4427 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4428 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004429 Result.NewTask = NewTask;
4430 Result.TaskEntry = TaskEntry;
4431 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4432 Result.TDBase = TDBase;
4433 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4434 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004435}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004436
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004437void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4438 const OMPExecutableDirective &D,
4439 llvm::Value *TaskFunction,
4440 QualType SharedsTy, Address Shareds,
4441 const Expr *IfCond,
4442 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004443 if (!CGF.HaveInsertPoint())
4444 return;
4445
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004446 TaskResultTy Result =
4447 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4448 llvm::Value *NewTask = Result.NewTask;
4449 llvm::Value *TaskEntry = Result.TaskEntry;
4450 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4451 LValue TDBase = Result.TDBase;
4452 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004453 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004454 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004455 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004456 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004457 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004458 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004459 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004460 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4461 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004462 QualType FlagsTy =
4463 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004464 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4465 if (KmpDependInfoTy.isNull()) {
4466 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4467 KmpDependInfoRD->startDefinition();
4468 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4469 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4470 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4471 KmpDependInfoRD->completeDefinition();
4472 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004473 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004474 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004475 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004476 // Define type kmp_depend_info[<Dependences.size()>];
4477 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004478 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004479 ArrayType::Normal, /*IndexTypeQuals=*/0);
4480 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004481 DependenciesArray =
4482 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004483 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004484 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004485 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004486 llvm::Value *Size;
4487 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004488 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4489 LValue UpAddrLVal =
4490 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4491 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004492 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004493 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004494 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004495 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4496 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004497 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004498 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004499 auto Base = CGF.MakeAddrLValue(
4500 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004501 KmpDependInfoTy);
4502 // deps[i].base_addr = &<Dependences[i].second>;
4503 auto BaseAddrLVal = CGF.EmitLValueForField(
4504 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004505 CGF.EmitStoreOfScalar(
4506 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4507 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004508 // deps[i].len = sizeof(<Dependences[i].second>);
4509 auto LenLVal = CGF.EmitLValueForField(
4510 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4511 CGF.EmitStoreOfScalar(Size, LenLVal);
4512 // deps[i].flags = <Dependences[i].first>;
4513 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004514 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004515 case OMPC_DEPEND_in:
4516 DepKind = DepIn;
4517 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004518 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004519 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004520 case OMPC_DEPEND_inout:
4521 DepKind = DepInOut;
4522 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004523 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004524 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004525 case OMPC_DEPEND_unknown:
4526 llvm_unreachable("Unknown task dependence type");
4527 }
4528 auto FlagsLVal = CGF.EmitLValueForField(
4529 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4530 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4531 FlagsLVal);
4532 }
John McCall7f416cc2015-09-08 08:05:57 +00004533 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4534 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004535 CGF.VoidPtrTy);
4536 }
4537
Alexey Bataev62b63b12015-03-10 07:28:44 +00004538 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4539 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004540 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4541 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4542 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4543 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004544 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004545 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004546 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4547 llvm::Value *DepTaskArgs[7];
4548 if (NumDependencies) {
4549 DepTaskArgs[0] = UpLoc;
4550 DepTaskArgs[1] = ThreadID;
4551 DepTaskArgs[2] = NewTask;
4552 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4553 DepTaskArgs[4] = DependenciesArray.getPointer();
4554 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4555 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4556 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004557 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4558 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004559 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004560 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004561 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4562 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4563 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4564 }
John McCall7f416cc2015-09-08 08:05:57 +00004565 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004566 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004567 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004568 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004569 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004570 TaskArgs);
4571 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004572 // Check if parent region is untied and build return for untied task;
4573 if (auto *Region =
4574 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4575 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004576 };
John McCall7f416cc2015-09-08 08:05:57 +00004577
4578 llvm::Value *DepWaitTaskArgs[6];
4579 if (NumDependencies) {
4580 DepWaitTaskArgs[0] = UpLoc;
4581 DepWaitTaskArgs[1] = ThreadID;
4582 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4583 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4584 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4585 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4586 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004587 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004588 NumDependencies, &DepWaitTaskArgs,
4589 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004590 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004591 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4592 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4593 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4594 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4595 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004596 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004597 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004598 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004599 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004600 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4601 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004602 Action.Enter(CGF);
4603 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004604 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004605 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004606 };
4607
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004608 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4609 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004610 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4611 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004612 RegionCodeGenTy RCG(CodeGen);
4613 CommonActionTy Action(
4614 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4615 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4616 RCG.setAction(Action);
4617 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004618 };
John McCall7f416cc2015-09-08 08:05:57 +00004619
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004620 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004621 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004622 else {
4623 RegionCodeGenTy ThenRCG(ThenCodeGen);
4624 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004625 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004626}
4627
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004628void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4629 const OMPLoopDirective &D,
4630 llvm::Value *TaskFunction,
4631 QualType SharedsTy, Address Shareds,
4632 const Expr *IfCond,
4633 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004634 if (!CGF.HaveInsertPoint())
4635 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004636 TaskResultTy Result =
4637 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004638 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4639 // libcall.
4640 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4641 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4642 // sched, kmp_uint64 grainsize, void *task_dup);
4643 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4644 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4645 llvm::Value *IfVal;
4646 if (IfCond) {
4647 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4648 /*isSigned=*/true);
4649 } else
4650 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4651
4652 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004653 Result.TDBase,
4654 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004655 auto *LBVar =
4656 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4657 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4658 /*IsInitializer=*/true);
4659 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004660 Result.TDBase,
4661 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004662 auto *UBVar =
4663 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4664 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4665 /*IsInitializer=*/true);
4666 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004667 Result.TDBase,
4668 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004669 auto *StVar =
4670 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4671 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4672 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004673 // Store reductions address.
4674 LValue RedLVal = CGF.EmitLValueForField(
4675 Result.TDBase,
4676 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4677 if (Data.Reductions)
4678 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4679 else {
4680 CGF.EmitNullInitialization(RedLVal.getAddress(),
4681 CGF.getContext().VoidPtrTy);
4682 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004683 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004684 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004685 UpLoc,
4686 ThreadID,
4687 Result.NewTask,
4688 IfVal,
4689 LBLVal.getPointer(),
4690 UBLVal.getPointer(),
4691 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4692 llvm::ConstantInt::getNullValue(
4693 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004694 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004695 CGF.IntTy, Data.Schedule.getPointer()
4696 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004697 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004698 Data.Schedule.getPointer()
4699 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004700 /*isSigned=*/false)
4701 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004702 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4703 Result.TaskDupFn, CGF.VoidPtrTy)
4704 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004705 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4706}
4707
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004708/// \brief Emit reduction operation for each element of array (required for
4709/// array sections) LHS op = RHS.
4710/// \param Type Type of array.
4711/// \param LHSVar Variable on the left side of the reduction operation
4712/// (references element of array in original variable).
4713/// \param RHSVar Variable on the right side of the reduction operation
4714/// (references element of array in original variable).
4715/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4716/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004717static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004718 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4719 const VarDecl *RHSVar,
4720 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4721 const Expr *, const Expr *)> &RedOpGen,
4722 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4723 const Expr *UpExpr = nullptr) {
4724 // Perform element-by-element initialization.
4725 QualType ElementTy;
4726 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4727 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4728
4729 // Drill down to the base element type on both arrays.
4730 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4731 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4732
4733 auto RHSBegin = RHSAddr.getPointer();
4734 auto LHSBegin = LHSAddr.getPointer();
4735 // Cast from pointer to array type to pointer to single element.
4736 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4737 // The basic structure here is a while-do loop.
4738 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4739 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4740 auto IsEmpty =
4741 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4742 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4743
4744 // Enter the loop body, making that address the current address.
4745 auto EntryBB = CGF.Builder.GetInsertBlock();
4746 CGF.EmitBlock(BodyBB);
4747
4748 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4749
4750 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4751 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4752 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4753 Address RHSElementCurrent =
4754 Address(RHSElementPHI,
4755 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4756
4757 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4758 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4759 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4760 Address LHSElementCurrent =
4761 Address(LHSElementPHI,
4762 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4763
4764 // Emit copy.
4765 CodeGenFunction::OMPPrivateScope Scope(CGF);
4766 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4767 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4768 Scope.Privatize();
4769 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4770 Scope.ForceCleanup();
4771
4772 // Shift the address forward by one element.
4773 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4774 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4775 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4776 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4777 // Check whether we've reached the end.
4778 auto Done =
4779 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4780 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4781 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4782 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4783
4784 // Done.
4785 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4786}
4787
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004788/// Emit reduction combiner. If the combiner is a simple expression emit it as
4789/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4790/// UDR combiner function.
4791static void emitReductionCombiner(CodeGenFunction &CGF,
4792 const Expr *ReductionOp) {
4793 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4794 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4795 if (auto *DRE =
4796 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4797 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4798 std::pair<llvm::Function *, llvm::Function *> Reduction =
4799 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4800 RValue Func = RValue::get(Reduction.first);
4801 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4802 CGF.EmitIgnoredExpr(ReductionOp);
4803 return;
4804 }
4805 CGF.EmitIgnoredExpr(ReductionOp);
4806}
4807
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004808llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4809 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4810 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4811 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004812 auto &C = CGM.getContext();
4813
4814 // void reduction_func(void *LHSArg, void *RHSArg);
4815 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004816 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4817 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004818 Args.push_back(&LHSArg);
4819 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004820 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004821 auto *Fn = llvm::Function::Create(
4822 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4823 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004824 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004825 CodeGenFunction CGF(CGM);
4826 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4827
4828 // Dst = (void*[n])(LHSArg);
4829 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004830 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4831 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4832 ArgsType), CGF.getPointerAlign());
4833 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4834 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4835 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004836
4837 // ...
4838 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4839 // ...
4840 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004841 auto IPriv = Privates.begin();
4842 unsigned Idx = 0;
4843 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004844 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4845 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004846 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004847 });
4848 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4849 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004850 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004851 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004852 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004853 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004854 // Get array size and emit VLA type.
4855 ++Idx;
4856 Address Elem =
4857 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4858 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004859 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4860 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004861 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004862 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004863 CGF.EmitVariablyModifiedType(PrivTy);
4864 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004865 }
4866 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004867 IPriv = Privates.begin();
4868 auto ILHS = LHSExprs.begin();
4869 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004870 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004871 if ((*IPriv)->getType()->isArrayType()) {
4872 // Emit reduction for array section.
4873 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4874 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004875 EmitOMPAggregateReduction(
4876 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4877 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4878 emitReductionCombiner(CGF, E);
4879 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004880 } else
4881 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004882 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004883 ++IPriv;
4884 ++ILHS;
4885 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004886 }
4887 Scope.ForceCleanup();
4888 CGF.FinishFunction();
4889 return Fn;
4890}
4891
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004892void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4893 const Expr *ReductionOp,
4894 const Expr *PrivateRef,
4895 const DeclRefExpr *LHS,
4896 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004897 if (PrivateRef->getType()->isArrayType()) {
4898 // Emit reduction for array section.
4899 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4900 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4901 EmitOMPAggregateReduction(
4902 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4903 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4904 emitReductionCombiner(CGF, ReductionOp);
4905 });
4906 } else
4907 // Emit reduction for array subscript or single variable.
4908 emitReductionCombiner(CGF, ReductionOp);
4909}
4910
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004911void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004912 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004913 ArrayRef<const Expr *> LHSExprs,
4914 ArrayRef<const Expr *> RHSExprs,
4915 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004916 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004917 if (!CGF.HaveInsertPoint())
4918 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004919
4920 bool WithNowait = Options.WithNowait;
4921 bool SimpleReduction = Options.SimpleReduction;
4922
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004923 // Next code should be emitted for reduction:
4924 //
4925 // static kmp_critical_name lock = { 0 };
4926 //
4927 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4928 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4929 // ...
4930 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4931 // *(Type<n>-1*)rhs[<n>-1]);
4932 // }
4933 //
4934 // ...
4935 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4936 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4937 // RedList, reduce_func, &<lock>)) {
4938 // case 1:
4939 // ...
4940 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4941 // ...
4942 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4943 // break;
4944 // case 2:
4945 // ...
4946 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4947 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004948 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004949 // break;
4950 // default:;
4951 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004952 //
4953 // if SimpleReduction is true, only the next code is generated:
4954 // ...
4955 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4956 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004957
4958 auto &C = CGM.getContext();
4959
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004960 if (SimpleReduction) {
4961 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004962 auto IPriv = Privates.begin();
4963 auto ILHS = LHSExprs.begin();
4964 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004965 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004966 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4967 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004968 ++IPriv;
4969 ++ILHS;
4970 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004971 }
4972 return;
4973 }
4974
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004975 // 1. Build a list of reduction variables.
4976 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004977 auto Size = RHSExprs.size();
4978 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004979 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004980 // Reserve place for array size.
4981 ++Size;
4982 }
4983 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004984 QualType ReductionArrayTy =
4985 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4986 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004987 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004988 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004989 auto IPriv = Privates.begin();
4990 unsigned Idx = 0;
4991 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004992 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004993 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004994 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004995 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004996 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4997 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004998 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004999 // Store array size.
5000 ++Idx;
5001 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5002 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005003 llvm::Value *Size = CGF.Builder.CreateIntCast(
5004 CGF.getVLASize(
5005 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5006 .first,
5007 CGF.SizeTy, /*isSigned=*/false);
5008 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5009 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005010 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005011 }
5012
5013 // 2. Emit reduce_func().
5014 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005015 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5016 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005017
5018 // 3. Create static kmp_critical_name lock = { 0 };
5019 auto *Lock = getCriticalRegionLock(".reduction");
5020
5021 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5022 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005023 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005024 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005025 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005026 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5027 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005028 llvm::Value *Args[] = {
5029 IdentTLoc, // ident_t *<loc>
5030 ThreadId, // i32 <gtid>
5031 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5032 ReductionArrayTySize, // size_type sizeof(RedList)
5033 RL, // void *RedList
5034 ReductionFn, // void (*) (void *, void *) <reduce_func>
5035 Lock // kmp_critical_name *&<lock>
5036 };
5037 auto Res = CGF.EmitRuntimeCall(
5038 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5039 : OMPRTL__kmpc_reduce),
5040 Args);
5041
5042 // 5. Build switch(res)
5043 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5044 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5045
5046 // 6. Build case 1:
5047 // ...
5048 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5049 // ...
5050 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5051 // break;
5052 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5053 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5054 CGF.EmitBlock(Case1BB);
5055
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005056 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5057 llvm::Value *EndArgs[] = {
5058 IdentTLoc, // ident_t *<loc>
5059 ThreadId, // i32 <gtid>
5060 Lock // kmp_critical_name *&<lock>
5061 };
5062 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5063 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005064 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005065 auto IPriv = Privates.begin();
5066 auto ILHS = LHSExprs.begin();
5067 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005068 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005069 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5070 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005071 ++IPriv;
5072 ++ILHS;
5073 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005074 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005075 };
5076 RegionCodeGenTy RCG(CodeGen);
5077 CommonActionTy Action(
5078 nullptr, llvm::None,
5079 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5080 : OMPRTL__kmpc_end_reduce),
5081 EndArgs);
5082 RCG.setAction(Action);
5083 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005084
5085 CGF.EmitBranch(DefaultBB);
5086
5087 // 7. Build case 2:
5088 // ...
5089 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5090 // ...
5091 // break;
5092 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5093 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5094 CGF.EmitBlock(Case2BB);
5095
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005096 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5097 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005098 auto ILHS = LHSExprs.begin();
5099 auto IRHS = RHSExprs.begin();
5100 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005101 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005102 const Expr *XExpr = nullptr;
5103 const Expr *EExpr = nullptr;
5104 const Expr *UpExpr = nullptr;
5105 BinaryOperatorKind BO = BO_Comma;
5106 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5107 if (BO->getOpcode() == BO_Assign) {
5108 XExpr = BO->getLHS();
5109 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005110 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005111 }
5112 // Try to emit update expression as a simple atomic.
5113 auto *RHSExpr = UpExpr;
5114 if (RHSExpr) {
5115 // Analyze RHS part of the whole expression.
5116 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5117 RHSExpr->IgnoreParenImpCasts())) {
5118 // If this is a conditional operator, analyze its condition for
5119 // min/max reduction operator.
5120 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005121 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005122 if (auto *BORHS =
5123 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5124 EExpr = BORHS->getRHS();
5125 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005126 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005127 }
5128 if (XExpr) {
5129 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005130 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005131 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5132 const Expr *EExpr, const Expr *UpExpr) {
5133 LValue X = CGF.EmitLValue(XExpr);
5134 RValue E;
5135 if (EExpr)
5136 E = CGF.EmitAnyExpr(EExpr);
5137 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005138 X, E, BO, /*IsXLHSInRHSPart=*/true,
5139 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005140 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005141 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5142 PrivateScope.addPrivate(
5143 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5144 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5145 CGF.emitOMPSimpleStore(
5146 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5147 VD->getType().getNonReferenceType(), Loc);
5148 return LHSTemp;
5149 });
5150 (void)PrivateScope.Privatize();
5151 return CGF.EmitAnyExpr(UpExpr);
5152 });
5153 };
5154 if ((*IPriv)->getType()->isArrayType()) {
5155 // Emit atomic reduction for array section.
5156 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5157 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5158 AtomicRedGen, XExpr, EExpr, UpExpr);
5159 } else
5160 // Emit atomic reduction for array subscript or single variable.
5161 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5162 } else {
5163 // Emit as a critical region.
5164 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5165 const Expr *, const Expr *) {
5166 auto &RT = CGF.CGM.getOpenMPRuntime();
5167 RT.emitCriticalRegion(
5168 CGF, ".atomic_reduction",
5169 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5170 Action.Enter(CGF);
5171 emitReductionCombiner(CGF, E);
5172 },
5173 Loc);
5174 };
5175 if ((*IPriv)->getType()->isArrayType()) {
5176 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5177 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5178 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5179 CritRedGen);
5180 } else
5181 CritRedGen(CGF, nullptr, nullptr, nullptr);
5182 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005183 ++ILHS;
5184 ++IRHS;
5185 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005186 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005187 };
5188 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5189 if (!WithNowait) {
5190 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5191 llvm::Value *EndArgs[] = {
5192 IdentTLoc, // ident_t *<loc>
5193 ThreadId, // i32 <gtid>
5194 Lock // kmp_critical_name *&<lock>
5195 };
5196 CommonActionTy Action(nullptr, llvm::None,
5197 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5198 EndArgs);
5199 AtomicRCG.setAction(Action);
5200 AtomicRCG(CGF);
5201 } else
5202 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005203
5204 CGF.EmitBranch(DefaultBB);
5205 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5206}
5207
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005208/// Generates unique name for artificial threadprivate variables.
5209/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5210static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5211 unsigned N) {
5212 SmallString<256> Buffer;
5213 llvm::raw_svector_ostream Out(Buffer);
5214 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5215 return Out.str();
5216}
5217
5218/// Emits reduction initializer function:
5219/// \code
5220/// void @.red_init(void* %arg) {
5221/// %0 = bitcast void* %arg to <type>*
5222/// store <type> <init>, <type>* %0
5223/// ret void
5224/// }
5225/// \endcode
5226static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5227 SourceLocation Loc,
5228 ReductionCodeGen &RCG, unsigned N) {
5229 auto &C = CGM.getContext();
5230 FunctionArgList Args;
5231 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5232 Args.emplace_back(&Param);
5233 auto &FnInfo =
5234 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5235 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5236 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5237 ".red_init.", &CGM.getModule());
5238 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5239 CodeGenFunction CGF(CGM);
5240 CGF.disableDebugInfo();
5241 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5242 Address PrivateAddr = CGF.EmitLoadOfPointer(
5243 CGF.GetAddrOfLocalVar(&Param),
5244 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5245 llvm::Value *Size = nullptr;
5246 // If the size of the reduction item is non-constant, load it from global
5247 // threadprivate variable.
5248 if (RCG.getSizes(N).second) {
5249 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5250 CGF, CGM.getContext().getSizeType(),
5251 generateUniqueName("reduction_size", Loc, N));
5252 Size =
5253 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5254 CGM.getContext().getSizeType(), SourceLocation());
5255 }
5256 RCG.emitAggregateType(CGF, N, Size);
5257 LValue SharedLVal;
5258 // If initializer uses initializer from declare reduction construct, emit a
5259 // pointer to the address of the original reduction item (reuired by reduction
5260 // initializer)
5261 if (RCG.usesReductionInitializer(N)) {
5262 Address SharedAddr =
5263 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5264 CGF, CGM.getContext().VoidPtrTy,
5265 generateUniqueName("reduction", Loc, N));
5266 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5267 } else {
5268 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5269 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5270 CGM.getContext().VoidPtrTy);
5271 }
5272 // Emit the initializer:
5273 // %0 = bitcast void* %arg to <type>*
5274 // store <type> <init>, <type>* %0
5275 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5276 [](CodeGenFunction &) { return false; });
5277 CGF.FinishFunction();
5278 return Fn;
5279}
5280
5281/// Emits reduction combiner function:
5282/// \code
5283/// void @.red_comb(void* %arg0, void* %arg1) {
5284/// %lhs = bitcast void* %arg0 to <type>*
5285/// %rhs = bitcast void* %arg1 to <type>*
5286/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5287/// store <type> %2, <type>* %lhs
5288/// ret void
5289/// }
5290/// \endcode
5291static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5292 SourceLocation Loc,
5293 ReductionCodeGen &RCG, unsigned N,
5294 const Expr *ReductionOp,
5295 const Expr *LHS, const Expr *RHS,
5296 const Expr *PrivateRef) {
5297 auto &C = CGM.getContext();
5298 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5299 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5300 FunctionArgList Args;
5301 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5302 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5303 Args.emplace_back(&ParamInOut);
5304 Args.emplace_back(&ParamIn);
5305 auto &FnInfo =
5306 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5307 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5308 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5309 ".red_comb.", &CGM.getModule());
5310 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5311 CodeGenFunction CGF(CGM);
5312 CGF.disableDebugInfo();
5313 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5314 llvm::Value *Size = nullptr;
5315 // If the size of the reduction item is non-constant, load it from global
5316 // threadprivate variable.
5317 if (RCG.getSizes(N).second) {
5318 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5319 CGF, CGM.getContext().getSizeType(),
5320 generateUniqueName("reduction_size", Loc, N));
5321 Size =
5322 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5323 CGM.getContext().getSizeType(), SourceLocation());
5324 }
5325 RCG.emitAggregateType(CGF, N, Size);
5326 // Remap lhs and rhs variables to the addresses of the function arguments.
5327 // %lhs = bitcast void* %arg0 to <type>*
5328 // %rhs = bitcast void* %arg1 to <type>*
5329 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5330 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5331 // Pull out the pointer to the variable.
5332 Address PtrAddr = CGF.EmitLoadOfPointer(
5333 CGF.GetAddrOfLocalVar(&ParamInOut),
5334 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5335 return CGF.Builder.CreateElementBitCast(
5336 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5337 });
5338 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5339 // Pull out the pointer to the variable.
5340 Address PtrAddr = CGF.EmitLoadOfPointer(
5341 CGF.GetAddrOfLocalVar(&ParamIn),
5342 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5343 return CGF.Builder.CreateElementBitCast(
5344 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5345 });
5346 PrivateScope.Privatize();
5347 // Emit the combiner body:
5348 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5349 // store <type> %2, <type>* %lhs
5350 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5351 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5352 cast<DeclRefExpr>(RHS));
5353 CGF.FinishFunction();
5354 return Fn;
5355}
5356
5357/// Emits reduction finalizer function:
5358/// \code
5359/// void @.red_fini(void* %arg) {
5360/// %0 = bitcast void* %arg to <type>*
5361/// <destroy>(<type>* %0)
5362/// ret void
5363/// }
5364/// \endcode
5365static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5366 SourceLocation Loc,
5367 ReductionCodeGen &RCG, unsigned N) {
5368 if (!RCG.needCleanups(N))
5369 return nullptr;
5370 auto &C = CGM.getContext();
5371 FunctionArgList Args;
5372 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5373 Args.emplace_back(&Param);
5374 auto &FnInfo =
5375 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5376 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5377 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5378 ".red_fini.", &CGM.getModule());
5379 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5380 CodeGenFunction CGF(CGM);
5381 CGF.disableDebugInfo();
5382 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5383 Address PrivateAddr = CGF.EmitLoadOfPointer(
5384 CGF.GetAddrOfLocalVar(&Param),
5385 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5386 llvm::Value *Size = nullptr;
5387 // If the size of the reduction item is non-constant, load it from global
5388 // threadprivate variable.
5389 if (RCG.getSizes(N).second) {
5390 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5391 CGF, CGM.getContext().getSizeType(),
5392 generateUniqueName("reduction_size", Loc, N));
5393 Size =
5394 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5395 CGM.getContext().getSizeType(), SourceLocation());
5396 }
5397 RCG.emitAggregateType(CGF, N, Size);
5398 // Emit the finalizer body:
5399 // <destroy>(<type>* %0)
5400 RCG.emitCleanups(CGF, N, PrivateAddr);
5401 CGF.FinishFunction();
5402 return Fn;
5403}
5404
5405llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5406 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5407 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5408 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5409 return nullptr;
5410
5411 // Build typedef struct:
5412 // kmp_task_red_input {
5413 // void *reduce_shar; // shared reduction item
5414 // size_t reduce_size; // size of data item
5415 // void *reduce_init; // data initialization routine
5416 // void *reduce_fini; // data finalization routine
5417 // void *reduce_comb; // data combiner routine
5418 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5419 // } kmp_task_red_input_t;
5420 ASTContext &C = CGM.getContext();
5421 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5422 RD->startDefinition();
5423 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5424 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5425 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5426 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5427 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5428 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5429 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5430 RD->completeDefinition();
5431 QualType RDType = C.getRecordType(RD);
5432 unsigned Size = Data.ReductionVars.size();
5433 llvm::APInt ArraySize(/*numBits=*/64, Size);
5434 QualType ArrayRDType = C.getConstantArrayType(
5435 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5436 // kmp_task_red_input_t .rd_input.[Size];
5437 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5438 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5439 Data.ReductionOps);
5440 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5441 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5442 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5443 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5444 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5445 TaskRedInput.getPointer(), Idxs,
5446 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5447 ".rd_input.gep.");
5448 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5449 // ElemLVal.reduce_shar = &Shareds[Cnt];
5450 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5451 RCG.emitSharedLValue(CGF, Cnt);
5452 llvm::Value *CastedShared =
5453 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5454 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5455 RCG.emitAggregateType(CGF, Cnt);
5456 llvm::Value *SizeValInChars;
5457 llvm::Value *SizeVal;
5458 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5459 // We use delayed creation/initialization for VLAs, array sections and
5460 // custom reduction initializations. It is required because runtime does not
5461 // provide the way to pass the sizes of VLAs/array sections to
5462 // initializer/combiner/finalizer functions and does not pass the pointer to
5463 // original reduction item to the initializer. Instead threadprivate global
5464 // variables are used to store these values and use them in the functions.
5465 bool DelayedCreation = !!SizeVal;
5466 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5467 /*isSigned=*/false);
5468 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5469 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5470 // ElemLVal.reduce_init = init;
5471 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5472 llvm::Value *InitAddr =
5473 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5474 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5475 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5476 // ElemLVal.reduce_fini = fini;
5477 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5478 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5479 llvm::Value *FiniAddr = Fini
5480 ? CGF.EmitCastToVoidPtr(Fini)
5481 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5482 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5483 // ElemLVal.reduce_comb = comb;
5484 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5485 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5486 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5487 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5488 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5489 // ElemLVal.flags = 0;
5490 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5491 if (DelayedCreation) {
5492 CGF.EmitStoreOfScalar(
5493 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5494 FlagsLVal);
5495 } else
5496 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5497 }
5498 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5499 // *data);
5500 llvm::Value *Args[] = {
5501 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5502 /*isSigned=*/true),
5503 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5504 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5505 CGM.VoidPtrTy)};
5506 return CGF.EmitRuntimeCall(
5507 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5508}
5509
5510void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5511 SourceLocation Loc,
5512 ReductionCodeGen &RCG,
5513 unsigned N) {
5514 auto Sizes = RCG.getSizes(N);
5515 // Emit threadprivate global variable if the type is non-constant
5516 // (Sizes.second = nullptr).
5517 if (Sizes.second) {
5518 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5519 /*isSigned=*/false);
5520 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5521 CGF, CGM.getContext().getSizeType(),
5522 generateUniqueName("reduction_size", Loc, N));
5523 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5524 }
5525 // Store address of the original reduction item if custom initializer is used.
5526 if (RCG.usesReductionInitializer(N)) {
5527 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5528 CGF, CGM.getContext().VoidPtrTy,
5529 generateUniqueName("reduction", Loc, N));
5530 CGF.Builder.CreateStore(
5531 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5532 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5533 SharedAddr, /*IsVolatile=*/false);
5534 }
5535}
5536
5537Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5538 SourceLocation Loc,
5539 llvm::Value *ReductionsPtr,
5540 LValue SharedLVal) {
5541 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5542 // *d);
5543 llvm::Value *Args[] = {
5544 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5545 /*isSigned=*/true),
5546 ReductionsPtr,
5547 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5548 CGM.VoidPtrTy)};
5549 return Address(
5550 CGF.EmitRuntimeCall(
5551 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5552 SharedLVal.getAlignment());
5553}
5554
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005555void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5556 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005557 if (!CGF.HaveInsertPoint())
5558 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005559 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5560 // global_tid);
5561 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5562 // Ignore return result until untied tasks are supported.
5563 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005564 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5565 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005566}
5567
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005568void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005569 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005570 const RegionCodeGenTy &CodeGen,
5571 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005572 if (!CGF.HaveInsertPoint())
5573 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005574 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005575 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005576}
5577
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005578namespace {
5579enum RTCancelKind {
5580 CancelNoreq = 0,
5581 CancelParallel = 1,
5582 CancelLoop = 2,
5583 CancelSections = 3,
5584 CancelTaskgroup = 4
5585};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005586} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005587
5588static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5589 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005590 if (CancelRegion == OMPD_parallel)
5591 CancelKind = CancelParallel;
5592 else if (CancelRegion == OMPD_for)
5593 CancelKind = CancelLoop;
5594 else if (CancelRegion == OMPD_sections)
5595 CancelKind = CancelSections;
5596 else {
5597 assert(CancelRegion == OMPD_taskgroup);
5598 CancelKind = CancelTaskgroup;
5599 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005600 return CancelKind;
5601}
5602
5603void CGOpenMPRuntime::emitCancellationPointCall(
5604 CodeGenFunction &CGF, SourceLocation Loc,
5605 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005606 if (!CGF.HaveInsertPoint())
5607 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005608 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5609 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005610 if (auto *OMPRegionInfo =
5611 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005612 // For 'cancellation point taskgroup', the task region info may not have a
5613 // cancel. This may instead happen in another adjacent task.
5614 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005615 llvm::Value *Args[] = {
5616 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5617 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005618 // Ignore return result until untied tasks are supported.
5619 auto *Result = CGF.EmitRuntimeCall(
5620 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5621 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005622 // exit from construct;
5623 // }
5624 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5625 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5626 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5627 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5628 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005629 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005630 auto CancelDest =
5631 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005632 CGF.EmitBranchThroughCleanup(CancelDest);
5633 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5634 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005635 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005636}
5637
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005638void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005639 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005640 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005641 if (!CGF.HaveInsertPoint())
5642 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005643 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5644 // kmp_int32 cncl_kind);
5645 if (auto *OMPRegionInfo =
5646 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005647 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5648 PrePostActionTy &) {
5649 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005650 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005651 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005652 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5653 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005654 auto *Result = CGF.EmitRuntimeCall(
5655 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005656 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005657 // exit from construct;
5658 // }
5659 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5660 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5661 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5662 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5663 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005664 // exit from construct;
5665 auto CancelDest =
5666 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5667 CGF.EmitBranchThroughCleanup(CancelDest);
5668 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5669 };
5670 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005671 emitOMPIfClause(CGF, IfCond, ThenGen,
5672 [](CodeGenFunction &, PrePostActionTy &) {});
5673 else {
5674 RegionCodeGenTy ThenRCG(ThenGen);
5675 ThenRCG(CGF);
5676 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005677 }
5678}
Samuel Antaobed3c462015-10-02 16:14:20 +00005679
Samuel Antaoee8fb302016-01-06 13:42:12 +00005680/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005681/// consists of the file and device IDs as well as line number associated with
5682/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005683static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5684 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005685 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005686
5687 auto &SM = C.getSourceManager();
5688
5689 // The loc should be always valid and have a file ID (the user cannot use
5690 // #pragma directives in macros)
5691
5692 assert(Loc.isValid() && "Source location is expected to be always valid.");
5693 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5694
5695 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5696 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5697
5698 llvm::sys::fs::UniqueID ID;
5699 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5700 llvm_unreachable("Source file with target region no longer exists!");
5701
5702 DeviceID = ID.getDevice();
5703 FileID = ID.getFile();
5704 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005705}
5706
5707void CGOpenMPRuntime::emitTargetOutlinedFunction(
5708 const OMPExecutableDirective &D, StringRef ParentName,
5709 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005710 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005711 assert(!ParentName.empty() && "Invalid target region parent name!");
5712
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005713 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5714 IsOffloadEntry, CodeGen);
5715}
5716
5717void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5718 const OMPExecutableDirective &D, StringRef ParentName,
5719 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5720 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005721 // Create a unique name for the entry function using the source location
5722 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005723 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005724 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005725 //
5726 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005727 // mangled name of the function that encloses the target region and BB is the
5728 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005729
5730 unsigned DeviceID;
5731 unsigned FileID;
5732 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005733 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005734 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005735 SmallString<64> EntryFnName;
5736 {
5737 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005738 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5739 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005740 }
5741
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005742 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5743
Samuel Antaobed3c462015-10-02 16:14:20 +00005744 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005745 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005746 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005747
Samuel Antao6d004262016-06-16 18:39:34 +00005748 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005749
5750 // If this target outline function is not an offload entry, we don't need to
5751 // register it.
5752 if (!IsOffloadEntry)
5753 return;
5754
5755 // The target region ID is used by the runtime library to identify the current
5756 // target region, so it only has to be unique and not necessarily point to
5757 // anything. It could be the pointer to the outlined function that implements
5758 // the target region, but we aren't using that so that the compiler doesn't
5759 // need to keep that, and could therefore inline the host function if proven
5760 // worthwhile during optimization. In the other hand, if emitting code for the
5761 // device, the ID has to be the function address so that it can retrieved from
5762 // the offloading entry and launched by the runtime library. We also mark the
5763 // outlined function to have external linkage in case we are emitting code for
5764 // the device, because these functions will be entry points to the device.
5765
5766 if (CGM.getLangOpts().OpenMPIsDevice) {
5767 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5768 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5769 } else
5770 OutlinedFnID = new llvm::GlobalVariable(
5771 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5772 llvm::GlobalValue::PrivateLinkage,
5773 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5774
5775 // Register the information for the entry associated with this target region.
5776 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005777 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5778 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005779}
5780
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005781/// discard all CompoundStmts intervening between two constructs
5782static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5783 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5784 Body = CS->body_front();
5785
5786 return Body;
5787}
5788
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005789/// Emit the number of teams for a target directive. Inspect the num_teams
5790/// clause associated with a teams construct combined or closely nested
5791/// with the target directive.
5792///
5793/// Emit a team of size one for directives such as 'target parallel' that
5794/// have no associated teams construct.
5795///
5796/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005797static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005798emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5799 CodeGenFunction &CGF,
5800 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005801
5802 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5803 "teams directive expected to be "
5804 "emitted only for the host!");
5805
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005806 auto &Bld = CGF.Builder;
5807
5808 // If the target directive is combined with a teams directive:
5809 // Return the value in the num_teams clause, if any.
5810 // Otherwise, return 0 to denote the runtime default.
5811 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5812 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5813 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5814 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5815 /*IgnoreResultAssign*/ true);
5816 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5817 /*IsSigned=*/true);
5818 }
5819
5820 // The default value is 0.
5821 return Bld.getInt32(0);
5822 }
5823
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005824 // If the target directive is combined with a parallel directive but not a
5825 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005826 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5827 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005828
5829 // If the current target region has a teams region enclosed, we need to get
5830 // the number of teams to pass to the runtime function call. This is done
5831 // by generating the expression in a inlined region. This is required because
5832 // the expression is captured in the enclosing target environment when the
5833 // teams directive is not combined with target.
5834
5835 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5836
5837 // FIXME: Accommodate other combined directives with teams when they become
5838 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005839 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5840 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005841 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5842 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5843 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5844 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005845 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5846 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005847 }
5848
5849 // If we have an enclosed teams directive but no num_teams clause we use
5850 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005851 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005852 }
5853
5854 // No teams associated with the directive.
5855 return nullptr;
5856}
5857
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005858/// Emit the number of threads for a target directive. Inspect the
5859/// thread_limit clause associated with a teams construct combined or closely
5860/// nested with the target directive.
5861///
5862/// Emit the num_threads clause for directives such as 'target parallel' that
5863/// have no associated teams construct.
5864///
5865/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005866static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005867emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5868 CodeGenFunction &CGF,
5869 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005870
5871 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5872 "teams directive expected to be "
5873 "emitted only for the host!");
5874
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005875 auto &Bld = CGF.Builder;
5876
5877 //
5878 // If the target directive is combined with a teams directive:
5879 // Return the value in the thread_limit clause, if any.
5880 //
5881 // If the target directive is combined with a parallel directive:
5882 // Return the value in the num_threads clause, if any.
5883 //
5884 // If both clauses are set, select the minimum of the two.
5885 //
5886 // If neither teams or parallel combined directives set the number of threads
5887 // in a team, return 0 to denote the runtime default.
5888 //
5889 // If this is not a teams directive return nullptr.
5890
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005891 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5892 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005893 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5894 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005895 llvm::Value *ThreadLimitVal = nullptr;
5896
5897 if (const auto *ThreadLimitClause =
5898 D.getSingleClause<OMPThreadLimitClause>()) {
5899 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5900 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5901 /*IgnoreResultAssign*/ true);
5902 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5903 /*IsSigned=*/true);
5904 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005905
5906 if (const auto *NumThreadsClause =
5907 D.getSingleClause<OMPNumThreadsClause>()) {
5908 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5909 llvm::Value *NumThreads =
5910 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5911 /*IgnoreResultAssign*/ true);
5912 NumThreadsVal =
5913 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5914 }
5915
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005916 // Select the lesser of thread_limit and num_threads.
5917 if (NumThreadsVal)
5918 ThreadLimitVal = ThreadLimitVal
5919 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5920 ThreadLimitVal),
5921 NumThreadsVal, ThreadLimitVal)
5922 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005923
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005924 // Set default value passed to the runtime if either teams or a target
5925 // parallel type directive is found but no clause is specified.
5926 if (!ThreadLimitVal)
5927 ThreadLimitVal = DefaultThreadLimitVal;
5928
5929 return ThreadLimitVal;
5930 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005931
Samuel Antaob68e2db2016-03-03 16:20:23 +00005932 // If the current target region has a teams region enclosed, we need to get
5933 // the thread limit to pass to the runtime function call. This is done
5934 // by generating the expression in a inlined region. This is required because
5935 // the expression is captured in the enclosing target environment when the
5936 // teams directive is not combined with target.
5937
5938 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5939
5940 // FIXME: Accommodate other combined directives with teams when they become
5941 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005942 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5943 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005944 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5945 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5946 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5947 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5948 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5949 /*IsSigned=*/true);
5950 }
5951
5952 // If we have an enclosed teams directive but no thread_limit clause we use
5953 // the default value 0.
5954 return CGF.Builder.getInt32(0);
5955 }
5956
5957 // No teams associated with the directive.
5958 return nullptr;
5959}
5960
Samuel Antao86ace552016-04-27 22:40:57 +00005961namespace {
5962// \brief Utility to handle information from clauses associated with a given
5963// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5964// It provides a convenient interface to obtain the information and generate
5965// code for that information.
5966class MappableExprsHandler {
5967public:
5968 /// \brief Values for bit flags used to specify the mapping type for
5969 /// offloading.
5970 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005971 /// \brief Allocate memory on the device and move data from host to device.
5972 OMP_MAP_TO = 0x01,
5973 /// \brief Allocate memory on the device and move data from device to host.
5974 OMP_MAP_FROM = 0x02,
5975 /// \brief Always perform the requested mapping action on the element, even
5976 /// if it was already mapped before.
5977 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005978 /// \brief Delete the element from the device environment, ignoring the
5979 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005980 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00005981 /// \brief The element being mapped is a pointer-pointee pair; both the
5982 /// pointer and the pointee should be mapped.
5983 OMP_MAP_PTR_AND_OBJ = 0x10,
5984 /// \brief This flags signals that the base address of an entry should be
5985 /// passed to the target kernel as an argument.
5986 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005987 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00005988 /// in the current position for the data being mapped. Used when we have the
5989 /// use_device_ptr clause.
5990 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005991 /// \brief This flag signals that the reference being passed is a pointer to
5992 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00005993 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005994 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00005995 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00005996 /// Implicit map
5997 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00005998 };
5999
Samuel Antaocc10b852016-07-28 14:23:26 +00006000 /// Class that associates information with a base pointer to be passed to the
6001 /// runtime library.
6002 class BasePointerInfo {
6003 /// The base pointer.
6004 llvm::Value *Ptr = nullptr;
6005 /// The base declaration that refers to this device pointer, or null if
6006 /// there is none.
6007 const ValueDecl *DevPtrDecl = nullptr;
6008
6009 public:
6010 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6011 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6012 llvm::Value *operator*() const { return Ptr; }
6013 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6014 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6015 };
6016
6017 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006018 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
6019 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
6020
6021private:
6022 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006023 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006024
6025 /// \brief Function the directive is being generated for.
6026 CodeGenFunction &CGF;
6027
Samuel Antaod486f842016-05-26 16:53:38 +00006028 /// \brief Set of all first private variables in the current directive.
6029 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6030
Samuel Antao6890b092016-07-28 14:25:09 +00006031 /// Map between device pointer declarations and their expression components.
6032 /// The key value for declarations in 'this' is null.
6033 llvm::DenseMap<
6034 const ValueDecl *,
6035 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6036 DevPointersMap;
6037
Samuel Antao86ace552016-04-27 22:40:57 +00006038 llvm::Value *getExprTypeSize(const Expr *E) const {
6039 auto ExprTy = E->getType().getCanonicalType();
6040
6041 // Reference types are ignored for mapping purposes.
6042 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6043 ExprTy = RefTy->getPointeeType().getCanonicalType();
6044
6045 // Given that an array section is considered a built-in type, we need to
6046 // do the calculation based on the length of the section instead of relying
6047 // on CGF.getTypeSize(E->getType()).
6048 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6049 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6050 OAE->getBase()->IgnoreParenImpCasts())
6051 .getCanonicalType();
6052
6053 // If there is no length associated with the expression, that means we
6054 // are using the whole length of the base.
6055 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6056 return CGF.getTypeSize(BaseTy);
6057
6058 llvm::Value *ElemSize;
6059 if (auto *PTy = BaseTy->getAs<PointerType>())
6060 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6061 else {
6062 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6063 assert(ATy && "Expecting array type if not a pointer type.");
6064 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6065 }
6066
6067 // If we don't have a length at this point, that is because we have an
6068 // array section with a single element.
6069 if (!OAE->getLength())
6070 return ElemSize;
6071
6072 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6073 LengthVal =
6074 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6075 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6076 }
6077 return CGF.getTypeSize(ExprTy);
6078 }
6079
6080 /// \brief Return the corresponding bits for a given map clause modifier. Add
6081 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006082 /// map as the first one of a series of maps that relate to the same map
6083 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006084 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6085 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006086 bool AddIsTargetParamFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006087 unsigned Bits = 0u;
6088 switch (MapType) {
6089 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006090 case OMPC_MAP_release:
6091 // alloc and release is the default behavior in the runtime library, i.e.
6092 // if we don't pass any bits alloc/release that is what the runtime is
6093 // going to do. Therefore, we don't need to signal anything for these two
6094 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006095 break;
6096 case OMPC_MAP_to:
6097 Bits = OMP_MAP_TO;
6098 break;
6099 case OMPC_MAP_from:
6100 Bits = OMP_MAP_FROM;
6101 break;
6102 case OMPC_MAP_tofrom:
6103 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6104 break;
6105 case OMPC_MAP_delete:
6106 Bits = OMP_MAP_DELETE;
6107 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006108 default:
6109 llvm_unreachable("Unexpected map type!");
6110 break;
6111 }
6112 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006113 Bits |= OMP_MAP_PTR_AND_OBJ;
6114 if (AddIsTargetParamFlag)
6115 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006116 if (MapTypeModifier == OMPC_MAP_always)
6117 Bits |= OMP_MAP_ALWAYS;
6118 return Bits;
6119 }
6120
6121 /// \brief Return true if the provided expression is a final array section. A
6122 /// final array section, is one whose length can't be proved to be one.
6123 bool isFinalArraySectionExpression(const Expr *E) const {
6124 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6125
6126 // It is not an array section and therefore not a unity-size one.
6127 if (!OASE)
6128 return false;
6129
6130 // An array section with no colon always refer to a single element.
6131 if (OASE->getColonLoc().isInvalid())
6132 return false;
6133
6134 auto *Length = OASE->getLength();
6135
6136 // If we don't have a length we have to check if the array has size 1
6137 // for this dimension. Also, we should always expect a length if the
6138 // base type is pointer.
6139 if (!Length) {
6140 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6141 OASE->getBase()->IgnoreParenImpCasts())
6142 .getCanonicalType();
6143 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6144 return ATy->getSize().getSExtValue() != 1;
6145 // If we don't have a constant dimension length, we have to consider
6146 // the current section as having any size, so it is not necessarily
6147 // unitary. If it happen to be unity size, that's user fault.
6148 return true;
6149 }
6150
6151 // Check if the length evaluates to 1.
6152 llvm::APSInt ConstLength;
6153 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6154 return true; // Can have more that size 1.
6155
6156 return ConstLength.getSExtValue() != 1;
6157 }
6158
6159 /// \brief Generate the base pointers, section pointers, sizes and map type
6160 /// bits for the provided map type, map modifier, and expression components.
6161 /// \a IsFirstComponent should be set to true if the provided set of
6162 /// components is the first associated with a capture.
6163 void generateInfoForComponentList(
6164 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6165 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006166 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006167 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006168 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006169
6170 // The following summarizes what has to be generated for each map and the
6171 // types bellow. The generated information is expressed in this order:
6172 // base pointer, section pointer, size, flags
6173 // (to add to the ones that come from the map type and modifier).
6174 //
6175 // double d;
6176 // int i[100];
6177 // float *p;
6178 //
6179 // struct S1 {
6180 // int i;
6181 // float f[50];
6182 // }
6183 // struct S2 {
6184 // int i;
6185 // float f[50];
6186 // S1 s;
6187 // double *p;
6188 // struct S2 *ps;
6189 // }
6190 // S2 s;
6191 // S2 *ps;
6192 //
6193 // map(d)
6194 // &d, &d, sizeof(double), noflags
6195 //
6196 // map(i)
6197 // &i, &i, 100*sizeof(int), noflags
6198 //
6199 // map(i[1:23])
6200 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6201 //
6202 // map(p)
6203 // &p, &p, sizeof(float*), noflags
6204 //
6205 // map(p[1:24])
6206 // p, &p[1], 24*sizeof(float), noflags
6207 //
6208 // map(s)
6209 // &s, &s, sizeof(S2), noflags
6210 //
6211 // map(s.i)
6212 // &s, &(s.i), sizeof(int), noflags
6213 //
6214 // map(s.s.f)
6215 // &s, &(s.i.f), 50*sizeof(int), noflags
6216 //
6217 // map(s.p)
6218 // &s, &(s.p), sizeof(double*), noflags
6219 //
6220 // map(s.p[:22], s.a s.b)
6221 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006222 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006223 //
6224 // map(s.ps)
6225 // &s, &(s.ps), sizeof(S2*), noflags
6226 //
6227 // map(s.ps->s.i)
6228 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006229 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006230 //
6231 // map(s.ps->ps)
6232 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006233 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006234 //
6235 // map(s.ps->ps->ps)
6236 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006237 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6238 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006239 //
6240 // map(s.ps->ps->s.f[:22])
6241 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006242 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6243 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006244 //
6245 // map(ps)
6246 // &ps, &ps, sizeof(S2*), noflags
6247 //
6248 // map(ps->i)
6249 // ps, &(ps->i), sizeof(int), noflags
6250 //
6251 // map(ps->s.f)
6252 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6253 //
6254 // map(ps->p)
6255 // ps, &(ps->p), sizeof(double*), noflags
6256 //
6257 // map(ps->p[:22])
6258 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006259 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006260 //
6261 // map(ps->ps)
6262 // ps, &(ps->ps), sizeof(S2*), noflags
6263 //
6264 // map(ps->ps->s.i)
6265 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006266 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006267 //
6268 // map(ps->ps->ps)
6269 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006270 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006271 //
6272 // map(ps->ps->ps->ps)
6273 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006274 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6275 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006276 //
6277 // map(ps->ps->ps->s.f[:22])
6278 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006279 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6280 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006281
6282 // Track if the map information being generated is the first for a capture.
6283 bool IsCaptureFirstInfo = IsFirstComponentList;
6284
6285 // Scan the components from the base to the complete expression.
6286 auto CI = Components.rbegin();
6287 auto CE = Components.rend();
6288 auto I = CI;
6289
6290 // Track if the map information being generated is the first for a list of
6291 // components.
6292 bool IsExpressionFirstInfo = true;
6293 llvm::Value *BP = nullptr;
6294
6295 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6296 // The base is the 'this' pointer. The content of the pointer is going
6297 // to be the base of the field being mapped.
6298 BP = CGF.EmitScalarExpr(ME->getBase());
6299 } else {
6300 // The base is the reference to the variable.
6301 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006302 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006303
6304 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006305 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006306 // reference. References are ignored for mapping purposes.
6307 QualType Ty =
6308 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6309 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6310 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006311 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006312 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006313 .getPointer();
6314
6315 // We do not need to generate individual map information for the
6316 // pointer, it can be associated with the combined storage.
6317 ++I;
6318 }
6319 }
6320
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006321 unsigned DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006322 for (; I != CE; ++I) {
6323 auto Next = std::next(I);
6324
6325 // We need to generate the addresses and sizes if this is the last
6326 // component, if the component is a pointer or if it is an array section
6327 // whose length can't be proved to be one. If this is a pointer, it
6328 // becomes the base address for the following components.
6329
6330 // A final array section, is one whose length can't be proved to be one.
6331 bool IsFinalArraySection =
6332 isFinalArraySectionExpression(I->getAssociatedExpression());
6333
6334 // Get information on whether the element is a pointer. Have to do a
6335 // special treatment for array sections given that they are built-in
6336 // types.
6337 const auto *OASE =
6338 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6339 bool IsPointer =
6340 (OASE &&
6341 OMPArraySectionExpr::getBaseOriginalType(OASE)
6342 .getCanonicalType()
6343 ->isAnyPointerType()) ||
6344 I->getAssociatedExpression()->getType()->isAnyPointerType();
6345
6346 if (Next == CE || IsPointer || IsFinalArraySection) {
6347
6348 // If this is not the last component, we expect the pointer to be
6349 // associated with an array expression or member expression.
6350 assert((Next == CE ||
6351 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6352 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6353 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6354 "Unexpected expression");
6355
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006356 llvm::Value *LB =
6357 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006358 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6359
Samuel Antao03a3cec2016-07-27 22:52:16 +00006360 // If we have a member expression and the current component is a
6361 // reference, we have to map the reference too. Whenever we have a
6362 // reference, the section that reference refers to is going to be a
6363 // load instruction from the storage assigned to the reference.
6364 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6365 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6366 auto *LI = cast<llvm::LoadInst>(LB);
6367 auto *RefAddr = LI->getPointerOperand();
6368
6369 BasePointers.push_back(BP);
6370 Pointers.push_back(RefAddr);
6371 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006372 Types.push_back(DefaultFlags |
6373 getMapTypeBits(
6374 /*MapType*/ OMPC_MAP_alloc,
6375 /*MapTypeModifier=*/OMPC_MAP_unknown,
6376 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006377 IsExpressionFirstInfo = false;
6378 IsCaptureFirstInfo = false;
6379 // The reference will be the next base address.
6380 BP = RefAddr;
6381 }
6382
6383 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006384 Pointers.push_back(LB);
6385 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006386
Samuel Antao6782e942016-05-26 16:48:10 +00006387 // We need to add a pointer flag for each map that comes from the
6388 // same expression except for the first one. We also need to signal
6389 // this map is the first one that relates with the current capture
6390 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006391 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6392 !IsExpressionFirstInfo,
6393 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006394
6395 // If we have a final array section, we are done with this expression.
6396 if (IsFinalArraySection)
6397 break;
6398
6399 // The pointer becomes the base for the next element.
6400 if (Next != CE)
6401 BP = LB;
6402
6403 IsExpressionFirstInfo = false;
6404 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006405 }
6406 }
6407 }
6408
Samuel Antaod486f842016-05-26 16:53:38 +00006409 /// \brief Return the adjusted map modifiers if the declaration a capture
6410 /// refers to appears in a first-private clause. This is expected to be used
6411 /// only with directives that start with 'target'.
6412 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6413 unsigned CurrentModifiers) {
6414 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6415
6416 // A first private variable captured by reference will use only the
6417 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6418 // declaration is known as first-private in this handler.
6419 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
George Rokos065755d2017-11-07 18:27:04 +00006420 return MappableExprsHandler::OMP_MAP_PRIVATE |
Samuel Antaod486f842016-05-26 16:53:38 +00006421 MappableExprsHandler::OMP_MAP_TO;
6422
6423 // We didn't modify anything.
6424 return CurrentModifiers;
6425 }
6426
Samuel Antao86ace552016-04-27 22:40:57 +00006427public:
6428 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006429 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006430 // Extract firstprivate clause information.
6431 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6432 for (const auto *D : C->varlists())
6433 FirstPrivateDecls.insert(
6434 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006435 // Extract device pointer clause information.
6436 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6437 for (auto L : C->component_lists())
6438 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006439 }
Samuel Antao86ace552016-04-27 22:40:57 +00006440
6441 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006442 /// types for the extracted mappable expressions. Also, for each item that
6443 /// relates with a device pointer, a pair of the relevant declaration and
6444 /// index where it occurs is appended to the device pointers info array.
6445 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006446 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6447 MapFlagsArrayTy &Types) const {
6448 BasePointers.clear();
6449 Pointers.clear();
6450 Sizes.clear();
6451 Types.clear();
6452
6453 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006454 /// Kind that defines how a device pointer has to be returned.
6455 enum ReturnPointerKind {
6456 // Don't have to return any pointer.
6457 RPK_None,
6458 // Pointer is the base of the declaration.
6459 RPK_Base,
6460 // Pointer is a member of the base declaration - 'this'
6461 RPK_Member,
6462 // Pointer is a reference and a member of the base declaration - 'this'
6463 RPK_MemberReference,
6464 };
Samuel Antao86ace552016-04-27 22:40:57 +00006465 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006466 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6467 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6468 ReturnPointerKind ReturnDevicePointer = RPK_None;
6469 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006470
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006471 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006472 MapInfo(
6473 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6474 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006475 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006476 : Components(Components), MapType(MapType),
6477 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006478 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006479 };
6480
6481 // We have to process the component lists that relate with the same
6482 // declaration in a single chunk so that we can generate the map flags
6483 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006484 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006485
6486 // Helper function to fill the information map for the different supported
6487 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006488 auto &&InfoGen = [&Info](
6489 const ValueDecl *D,
6490 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6491 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006492 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006493 const ValueDecl *VD =
6494 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006495 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6496 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006497 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006498
Paul Robinson78fb1322016-08-01 22:12:46 +00006499 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006500 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006501 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006502 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006503 MapInfo::RPK_None, C->isImplicit());
6504 }
Paul Robinson15c84002016-07-29 20:46:16 +00006505 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006506 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006507 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006508 MapInfo::RPK_None, C->isImplicit());
6509 }
Paul Robinson15c84002016-07-29 20:46:16 +00006510 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006511 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006512 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006513 MapInfo::RPK_None, C->isImplicit());
6514 }
Samuel Antao86ace552016-04-27 22:40:57 +00006515
Samuel Antaocc10b852016-07-28 14:23:26 +00006516 // Look at the use_device_ptr clause information and mark the existing map
6517 // entries as such. If there is no map information for an entry in the
6518 // use_device_ptr list, we create one with map type 'alloc' and zero size
6519 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006520 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006521 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006522 for (auto L : C->component_lists()) {
6523 assert(!L.second.empty() && "Not expecting empty list of components!");
6524 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6525 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6526 auto *IE = L.second.back().getAssociatedExpression();
6527 // If the first component is a member expression, we have to look into
6528 // 'this', which maps to null in the map of map information. Otherwise
6529 // look directly for the information.
6530 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6531
6532 // We potentially have map information for this declaration already.
6533 // Look for the first set of components that refer to it.
6534 if (It != Info.end()) {
6535 auto CI = std::find_if(
6536 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6537 return MI.Components.back().getAssociatedDeclaration() == VD;
6538 });
6539 // If we found a map entry, signal that the pointer has to be returned
6540 // and move on to the next declaration.
6541 if (CI != It->second.end()) {
6542 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6543 ? (VD->getType()->isReferenceType()
6544 ? MapInfo::RPK_MemberReference
6545 : MapInfo::RPK_Member)
6546 : MapInfo::RPK_Base;
6547 continue;
6548 }
6549 }
6550
6551 // We didn't find any match in our map information - generate a zero
6552 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006553 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006554 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006555 this->CGF
6556 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006557 .getScalarVal();
6558 BasePointers.push_back({Ptr, VD});
6559 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006560 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00006561 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00006562 }
6563
Samuel Antao86ace552016-04-27 22:40:57 +00006564 for (auto &M : Info) {
6565 // We need to know when we generate information for the first component
6566 // associated with a capture, because the mapping flags depend on it.
6567 bool IsFirstComponentList = true;
6568 for (MapInfo &L : M.second) {
6569 assert(!L.Components.empty() &&
6570 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006571
6572 // Remember the current base pointer index.
6573 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006574 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006575 this->generateInfoForComponentList(
6576 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6577 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006578
6579 // If this entry relates with a device pointer, set the relevant
6580 // declaration and add the 'return pointer' flag.
6581 if (IsFirstComponentList &&
6582 L.ReturnDevicePointer != MapInfo::RPK_None) {
6583 // If the pointer is not the base of the map, we need to skip the
6584 // base. If it is a reference in a member field, we also need to skip
6585 // the map of the reference.
6586 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6587 ++CurrentBasePointersIdx;
6588 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6589 ++CurrentBasePointersIdx;
6590 }
6591 assert(BasePointers.size() > CurrentBasePointersIdx &&
6592 "Unexpected number of mapped base pointers.");
6593
6594 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6595 assert(RelevantVD &&
6596 "No relevant declaration related with device pointer??");
6597
6598 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00006599 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006600 }
Samuel Antao86ace552016-04-27 22:40:57 +00006601 IsFirstComponentList = false;
6602 }
6603 }
6604 }
6605
6606 /// \brief Generate the base pointers, section pointers, sizes and map types
6607 /// associated to a given capture.
6608 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006609 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006610 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006611 MapValuesArrayTy &Pointers,
6612 MapValuesArrayTy &Sizes,
6613 MapFlagsArrayTy &Types) const {
6614 assert(!Cap->capturesVariableArrayType() &&
6615 "Not expecting to generate map info for a variable array type!");
6616
6617 BasePointers.clear();
6618 Pointers.clear();
6619 Sizes.clear();
6620 Types.clear();
6621
Samuel Antao6890b092016-07-28 14:25:09 +00006622 // We need to know when we generating information for the first component
6623 // associated with a capture, because the mapping flags depend on it.
6624 bool IsFirstComponentList = true;
6625
Samuel Antao86ace552016-04-27 22:40:57 +00006626 const ValueDecl *VD =
6627 Cap->capturesThis()
6628 ? nullptr
6629 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6630
Samuel Antao6890b092016-07-28 14:25:09 +00006631 // If this declaration appears in a is_device_ptr clause we just have to
6632 // pass the pointer by value. If it is a reference to a declaration, we just
6633 // pass its value, otherwise, if it is a member expression, we need to map
6634 // 'to' the field.
6635 if (!VD) {
6636 auto It = DevPointersMap.find(VD);
6637 if (It != DevPointersMap.end()) {
6638 for (auto L : It->second) {
6639 generateInfoForComponentList(
6640 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006641 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6642 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006643 IsFirstComponentList = false;
6644 }
6645 return;
6646 }
6647 } else if (DevPointersMap.count(VD)) {
6648 BasePointers.push_back({Arg, VD});
6649 Pointers.push_back(Arg);
6650 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00006651 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00006652 return;
6653 }
6654
Paul Robinson78fb1322016-08-01 22:12:46 +00006655 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006656 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006657 for (auto L : C->decl_component_lists(VD)) {
6658 assert(L.first == VD &&
6659 "We got information for the wrong declaration??");
6660 assert(!L.second.empty() &&
6661 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006662 generateInfoForComponentList(
6663 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6664 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006665 IsFirstComponentList = false;
6666 }
6667
6668 return;
6669 }
Samuel Antaod486f842016-05-26 16:53:38 +00006670
6671 /// \brief Generate the default map information for a given capture \a CI,
6672 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006673 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6674 const FieldDecl &RI, llvm::Value *CV,
6675 MapBaseValuesArrayTy &CurBasePointers,
6676 MapValuesArrayTy &CurPointers,
6677 MapValuesArrayTy &CurSizes,
6678 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006679
6680 // Do the default mapping.
6681 if (CI.capturesThis()) {
6682 CurBasePointers.push_back(CV);
6683 CurPointers.push_back(CV);
6684 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6685 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6686 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006687 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006688 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006689 CurBasePointers.push_back(CV);
6690 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006691 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006692 // We have to signal to the runtime captures passed by value that are
6693 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00006694 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006695 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6696 } else {
6697 // Pointers are implicitly mapped with a zero size and no flags
6698 // (other than first map that is added for all implicit maps).
6699 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006700 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6701 }
6702 } else {
6703 assert(CI.capturesVariable() && "Expected captured reference.");
6704 CurBasePointers.push_back(CV);
6705 CurPointers.push_back(CV);
6706
6707 const ReferenceType *PtrTy =
6708 cast<ReferenceType>(RI.getType().getTypePtr());
6709 QualType ElementType = PtrTy->getPointeeType();
6710 CurSizes.push_back(CGF.getTypeSize(ElementType));
6711 // The default map type for a scalar/complex type is 'to' because by
6712 // default the value doesn't have to be retrieved. For an aggregate
6713 // type, the default is 'tofrom'.
6714 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006715 ? (OMP_MAP_TO | OMP_MAP_FROM)
6716 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006717
6718 // If we have a capture by reference we may need to add the private
6719 // pointer flag if the base declaration shows in some first-private
6720 // clause.
6721 CurMapTypes.back() =
6722 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6723 }
George Rokos065755d2017-11-07 18:27:04 +00006724 // Every default map produces a single argument which is a target parameter.
6725 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00006726 }
Samuel Antao86ace552016-04-27 22:40:57 +00006727};
Samuel Antaodf158d52016-04-27 22:58:19 +00006728
6729enum OpenMPOffloadingReservedDeviceIDs {
6730 /// \brief Device ID if the device was not defined, runtime should get it
6731 /// from environment variables in the spec.
6732 OMP_DEVICEID_UNDEF = -1,
6733};
6734} // anonymous namespace
6735
6736/// \brief Emit the arrays used to pass the captures and map information to the
6737/// offloading runtime library. If there is no map or capture information,
6738/// return nullptr by reference.
6739static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006740emitOffloadingArrays(CodeGenFunction &CGF,
6741 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006742 MappableExprsHandler::MapValuesArrayTy &Pointers,
6743 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006744 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6745 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006746 auto &CGM = CGF.CGM;
6747 auto &Ctx = CGF.getContext();
6748
Samuel Antaocc10b852016-07-28 14:23:26 +00006749 // Reset the array information.
6750 Info.clearArrayInfo();
6751 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006752
Samuel Antaocc10b852016-07-28 14:23:26 +00006753 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006754 // Detect if we have any capture size requiring runtime evaluation of the
6755 // size so that a constant array could be eventually used.
6756 bool hasRuntimeEvaluationCaptureSize = false;
6757 for (auto *S : Sizes)
6758 if (!isa<llvm::Constant>(S)) {
6759 hasRuntimeEvaluationCaptureSize = true;
6760 break;
6761 }
6762
Samuel Antaocc10b852016-07-28 14:23:26 +00006763 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006764 QualType PointerArrayType =
6765 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6766 /*IndexTypeQuals=*/0);
6767
Samuel Antaocc10b852016-07-28 14:23:26 +00006768 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006769 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006770 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006771 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6772
6773 // If we don't have any VLA types or other types that require runtime
6774 // evaluation, we can use a constant array for the map sizes, otherwise we
6775 // need to fill up the arrays as we do for the pointers.
6776 if (hasRuntimeEvaluationCaptureSize) {
6777 QualType SizeArrayType = Ctx.getConstantArrayType(
6778 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6779 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006780 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006781 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6782 } else {
6783 // We expect all the sizes to be constant, so we collect them to create
6784 // a constant array.
6785 SmallVector<llvm::Constant *, 16> ConstSizes;
6786 for (auto S : Sizes)
6787 ConstSizes.push_back(cast<llvm::Constant>(S));
6788
6789 auto *SizesArrayInit = llvm::ConstantArray::get(
6790 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6791 auto *SizesArrayGbl = new llvm::GlobalVariable(
6792 CGM.getModule(), SizesArrayInit->getType(),
6793 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6794 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006795 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006796 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006797 }
6798
6799 // The map types are always constant so we don't need to generate code to
6800 // fill arrays. Instead, we create an array constant.
6801 llvm::Constant *MapTypesArrayInit =
6802 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6803 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6804 CGM.getModule(), MapTypesArrayInit->getType(),
6805 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6806 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006807 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006808 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006809
Samuel Antaocc10b852016-07-28 14:23:26 +00006810 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6811 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006812 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006813 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6814 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006815 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6816 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006817 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6818 CGF.Builder.CreateStore(BPVal, BPAddr);
6819
Samuel Antaocc10b852016-07-28 14:23:26 +00006820 if (Info.requiresDevicePointerInfo())
6821 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6822 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6823
Samuel Antaodf158d52016-04-27 22:58:19 +00006824 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006825 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006826 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6827 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006828 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6829 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006830 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6831 CGF.Builder.CreateStore(PVal, PAddr);
6832
6833 if (hasRuntimeEvaluationCaptureSize) {
6834 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006835 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6836 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006837 /*Idx0=*/0,
6838 /*Idx1=*/i);
6839 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6840 CGF.Builder.CreateStore(
6841 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6842 SAddr);
6843 }
6844 }
6845 }
6846}
6847/// \brief Emit the arguments to be passed to the runtime library based on the
6848/// arrays of pointers, sizes and map types.
6849static void emitOffloadingArraysArgument(
6850 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6851 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006852 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006853 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006854 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006855 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006856 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6857 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006858 /*Idx0=*/0, /*Idx1=*/0);
6859 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006860 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6861 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006862 /*Idx0=*/0,
6863 /*Idx1=*/0);
6864 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006865 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006866 /*Idx0=*/0, /*Idx1=*/0);
6867 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006868 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6869 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006870 /*Idx0=*/0,
6871 /*Idx1=*/0);
6872 } else {
6873 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6874 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6875 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6876 MapTypesArrayArg =
6877 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6878 }
Samuel Antao86ace552016-04-27 22:40:57 +00006879}
6880
Samuel Antaobed3c462015-10-02 16:14:20 +00006881void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6882 const OMPExecutableDirective &D,
6883 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006884 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006885 const Expr *IfCond, const Expr *Device,
6886 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006887 if (!CGF.HaveInsertPoint())
6888 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006889
Samuel Antaoee8fb302016-01-06 13:42:12 +00006890 assert(OutlinedFn && "Invalid outlined function!");
6891
Samuel Antao86ace552016-04-27 22:40:57 +00006892 // Fill up the arrays with all the captured variables.
6893 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006894 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006895 MappableExprsHandler::MapValuesArrayTy Pointers;
6896 MappableExprsHandler::MapValuesArrayTy Sizes;
6897 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006898
Samuel Antaocc10b852016-07-28 14:23:26 +00006899 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006900 MappableExprsHandler::MapValuesArrayTy CurPointers;
6901 MappableExprsHandler::MapValuesArrayTy CurSizes;
6902 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6903
Samuel Antaod486f842016-05-26 16:53:38 +00006904 // Get mappable expression information.
6905 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006906
6907 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6908 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006909 auto CV = CapturedVars.begin();
6910 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6911 CE = CS.capture_end();
6912 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00006913 CurBasePointers.clear();
6914 CurPointers.clear();
6915 CurSizes.clear();
6916 CurMapTypes.clear();
6917
6918 // VLA sizes are passed to the outlined region by copy and do not have map
6919 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006920 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006921 CurBasePointers.push_back(*CV);
6922 CurPointers.push_back(*CV);
6923 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006924 // Copy to the device as an argument. No need to retrieve it.
George Rokos065755d2017-11-07 18:27:04 +00006925 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
6926 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
Samuel Antaobed3c462015-10-02 16:14:20 +00006927 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006928 // If we have any information in the map clause, we use it, otherwise we
6929 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006930 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006931 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006932 if (CurBasePointers.empty())
6933 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6934 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006935 }
Samuel Antao86ace552016-04-27 22:40:57 +00006936 // We expect to have at least an element of information for this capture.
6937 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6938 assert(CurBasePointers.size() == CurPointers.size() &&
6939 CurBasePointers.size() == CurSizes.size() &&
6940 CurBasePointers.size() == CurMapTypes.size() &&
6941 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006942
Samuel Antao86ace552016-04-27 22:40:57 +00006943 // The kernel args are always the first elements of the base pointers
6944 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006945 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006946 // We need to append the results of this capture to what we already have.
6947 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6948 Pointers.append(CurPointers.begin(), CurPointers.end());
6949 Sizes.append(CurSizes.begin(), CurSizes.end());
6950 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006951 }
6952
Samuel Antaobed3c462015-10-02 16:14:20 +00006953 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00006954 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6955 OutlinedFn, OutlinedFnID, &D,
6956 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006957 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006958 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006959 TargetDataInfo Info;
6960 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6961 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6962 Info.PointersArray, Info.SizesArray,
6963 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006964
6965 // On top of the arrays that were filled up, the target offloading call
6966 // takes as arguments the device id as well as the host pointer. The host
6967 // pointer is used by the runtime library to identify the current target
6968 // region, so it only has to be unique and not necessarily point to
6969 // anything. It could be the pointer to the outlined function that
6970 // implements the target region, but we aren't using that so that the
6971 // compiler doesn't need to keep that, and could therefore inline the host
6972 // function if proven worthwhile during optimization.
6973
Samuel Antaoee8fb302016-01-06 13:42:12 +00006974 // From this point on, we need to have an ID of the target region defined.
6975 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006976
6977 // Emit device ID if any.
6978 llvm::Value *DeviceID;
6979 if (Device)
6980 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006981 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006982 else
6983 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6984
Samuel Antaodf158d52016-04-27 22:58:19 +00006985 // Emit the number of elements in the offloading arrays.
6986 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6987
Samuel Antaob68e2db2016-03-03 16:20:23 +00006988 // Return value of the runtime offloading call.
6989 llvm::Value *Return;
6990
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006991 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6992 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006993
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006994 // The target region is an outlined function launched by the runtime
6995 // via calls __tgt_target() or __tgt_target_teams().
6996 //
6997 // __tgt_target() launches a target region with one team and one thread,
6998 // executing a serial region. This master thread may in turn launch
6999 // more threads within its team upon encountering a parallel region,
7000 // however, no additional teams can be launched on the device.
7001 //
7002 // __tgt_target_teams() launches a target region with one or more teams,
7003 // each with one or more threads. This call is required for target
7004 // constructs such as:
7005 // 'target teams'
7006 // 'target' / 'teams'
7007 // 'target teams distribute parallel for'
7008 // 'target parallel'
7009 // and so on.
7010 //
7011 // Note that on the host and CPU targets, the runtime implementation of
7012 // these calls simply call the outlined function without forking threads.
7013 // The outlined functions themselves have runtime calls to
7014 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7015 // the compiler in emitTeamsCall() and emitParallelCall().
7016 //
7017 // In contrast, on the NVPTX target, the implementation of
7018 // __tgt_target_teams() launches a GPU kernel with the requested number
7019 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007020 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007021 // If we have NumTeams defined this means that we have an enclosed teams
7022 // region. Therefore we also expect to have NumThreads defined. These two
7023 // values should be defined in the presence of a teams directive,
7024 // regardless of having any clauses associated. If the user is using teams
7025 // but no clauses, these two values will be the default that should be
7026 // passed to the runtime library - a 32-bit integer with the value zero.
7027 assert(NumThreads && "Thread limit expression should be available along "
7028 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007029 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007030 DeviceID, OutlinedFnID,
7031 PointerNum, Info.BasePointersArray,
7032 Info.PointersArray, Info.SizesArray,
7033 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007034 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007035 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007036 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007037 } else {
7038 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007039 DeviceID, OutlinedFnID,
7040 PointerNum, Info.BasePointersArray,
7041 Info.PointersArray, Info.SizesArray,
7042 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007043 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007044 OffloadingArgs);
7045 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007046
Alexey Bataev2a007e02017-10-02 14:20:58 +00007047 // Check the error code and execute the host version if required.
7048 llvm::BasicBlock *OffloadFailedBlock =
7049 CGF.createBasicBlock("omp_offload.failed");
7050 llvm::BasicBlock *OffloadContBlock =
7051 CGF.createBasicBlock("omp_offload.cont");
7052 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7053 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7054
7055 CGF.EmitBlock(OffloadFailedBlock);
7056 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7057 CGF.EmitBranch(OffloadContBlock);
7058
7059 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007060 };
7061
Samuel Antaoee8fb302016-01-06 13:42:12 +00007062 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007063 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7064 PrePostActionTy &) {
7065 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7066 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007067 };
7068
7069 // If we have a target function ID it means that we need to support
7070 // offloading, otherwise, just execute on the host. We need to execute on host
7071 // regardless of the conditional in the if clause if, e.g., the user do not
7072 // specify target triples.
7073 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007074 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007075 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007076 else {
7077 RegionCodeGenTy ThenRCG(ThenGen);
7078 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007079 }
7080 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007081 RegionCodeGenTy ElseRCG(ElseGen);
7082 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007083 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007084}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007085
7086void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7087 StringRef ParentName) {
7088 if (!S)
7089 return;
7090
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007091 // Codegen OMP target directives that offload compute to the device.
7092 bool requiresDeviceCodegen =
7093 isa<OMPExecutableDirective>(S) &&
7094 isOpenMPTargetExecutionDirective(
7095 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007096
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007097 if (requiresDeviceCodegen) {
7098 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007099 unsigned DeviceID;
7100 unsigned FileID;
7101 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007102 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007103 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007104
7105 // Is this a target region that should not be emitted as an entry point? If
7106 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007107 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7108 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007109 return;
7110
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007111 switch (S->getStmtClass()) {
7112 case Stmt::OMPTargetDirectiveClass:
7113 CodeGenFunction::EmitOMPTargetDeviceFunction(
7114 CGM, ParentName, cast<OMPTargetDirective>(*S));
7115 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007116 case Stmt::OMPTargetParallelDirectiveClass:
7117 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7118 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7119 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007120 case Stmt::OMPTargetTeamsDirectiveClass:
7121 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7122 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7123 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007124 case Stmt::OMPTargetParallelForDirectiveClass:
7125 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7126 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7127 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007128 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7129 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7130 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7131 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007132 default:
7133 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7134 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007135 return;
7136 }
7137
7138 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007139 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007140 return;
7141
7142 scanForTargetRegionsFunctions(
7143 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7144 ParentName);
7145 return;
7146 }
7147
7148 // If this is a lambda function, look into its body.
7149 if (auto *L = dyn_cast<LambdaExpr>(S))
7150 S = L->getBody();
7151
7152 // Keep looking for target regions recursively.
7153 for (auto *II : S->children())
7154 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007155}
7156
7157bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7158 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7159
7160 // If emitting code for the host, we do not process FD here. Instead we do
7161 // the normal code generation.
7162 if (!CGM.getLangOpts().OpenMPIsDevice)
7163 return false;
7164
7165 // Try to detect target regions in the function.
7166 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7167
Samuel Antao4b75b872016-12-12 19:26:31 +00007168 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007169 // scanning. Therefore, we signal that this function is completely dealt
7170 // with.
7171 return true;
7172}
7173
7174bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7175 if (!CGM.getLangOpts().OpenMPIsDevice)
7176 return false;
7177
7178 // Check if there are Ctors/Dtors in this declaration and look for target
7179 // regions in it. We use the complete variant to produce the kernel name
7180 // mangling.
7181 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7182 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7183 for (auto *Ctor : RD->ctors()) {
7184 StringRef ParentName =
7185 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7186 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7187 }
7188 auto *Dtor = RD->getDestructor();
7189 if (Dtor) {
7190 StringRef ParentName =
7191 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7192 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7193 }
7194 }
7195
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007196 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007197 // implemented yet). Therefore we signal that GD was processed in this case.
7198 return true;
7199}
7200
7201bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7202 auto *VD = GD.getDecl();
7203 if (isa<FunctionDecl>(VD))
7204 return emitTargetFunctions(GD);
7205
7206 return emitTargetGlobalVariable(GD);
7207}
7208
7209llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7210 // If we have offloading in the current module, we need to emit the entries
7211 // now and register the offloading descriptor.
7212 createOffloadEntriesAndInfoMetadata();
7213
7214 // Create and register the offloading binary descriptors. This is the main
7215 // entity that captures all the information about offloading in the current
7216 // compilation unit.
7217 return createOffloadingBinaryDescriptorRegistration();
7218}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007219
7220void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7221 const OMPExecutableDirective &D,
7222 SourceLocation Loc,
7223 llvm::Value *OutlinedFn,
7224 ArrayRef<llvm::Value *> CapturedVars) {
7225 if (!CGF.HaveInsertPoint())
7226 return;
7227
7228 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7229 CodeGenFunction::RunCleanupsScope Scope(CGF);
7230
7231 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7232 llvm::Value *Args[] = {
7233 RTLoc,
7234 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7235 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7236 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7237 RealArgs.append(std::begin(Args), std::end(Args));
7238 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7239
7240 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7241 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7242}
7243
7244void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007245 const Expr *NumTeams,
7246 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007247 SourceLocation Loc) {
7248 if (!CGF.HaveInsertPoint())
7249 return;
7250
7251 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7252
Carlo Bertollic6872252016-04-04 15:55:02 +00007253 llvm::Value *NumTeamsVal =
7254 (NumTeams)
7255 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7256 CGF.CGM.Int32Ty, /* isSigned = */ true)
7257 : CGF.Builder.getInt32(0);
7258
7259 llvm::Value *ThreadLimitVal =
7260 (ThreadLimit)
7261 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7262 CGF.CGM.Int32Ty, /* isSigned = */ true)
7263 : CGF.Builder.getInt32(0);
7264
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007265 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007266 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7267 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007268 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7269 PushNumTeamsArgs);
7270}
Samuel Antaodf158d52016-04-27 22:58:19 +00007271
Samuel Antaocc10b852016-07-28 14:23:26 +00007272void CGOpenMPRuntime::emitTargetDataCalls(
7273 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7274 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007275 if (!CGF.HaveInsertPoint())
7276 return;
7277
Samuel Antaocc10b852016-07-28 14:23:26 +00007278 // Action used to replace the default codegen action and turn privatization
7279 // off.
7280 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007281
7282 // Generate the code for the opening of the data environment. Capture all the
7283 // arguments of the runtime call by reference because they are used in the
7284 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007285 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7286 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007287 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007288 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007289 MappableExprsHandler::MapValuesArrayTy Pointers;
7290 MappableExprsHandler::MapValuesArrayTy Sizes;
7291 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7292
7293 // Get map clause information.
7294 MappableExprsHandler MCHandler(D, CGF);
7295 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007296
7297 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007298 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007299
7300 llvm::Value *BasePointersArrayArg = nullptr;
7301 llvm::Value *PointersArrayArg = nullptr;
7302 llvm::Value *SizesArrayArg = nullptr;
7303 llvm::Value *MapTypesArrayArg = nullptr;
7304 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007305 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007306
7307 // Emit device ID if any.
7308 llvm::Value *DeviceID = nullptr;
7309 if (Device)
7310 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7311 CGF.Int32Ty, /*isSigned=*/true);
7312 else
7313 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7314
7315 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007316 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007317
7318 llvm::Value *OffloadingArgs[] = {
7319 DeviceID, PointerNum, BasePointersArrayArg,
7320 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7321 auto &RT = CGF.CGM.getOpenMPRuntime();
7322 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7323 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007324
7325 // If device pointer privatization is required, emit the body of the region
7326 // here. It will have to be duplicated: with and without privatization.
7327 if (!Info.CaptureDeviceAddrMap.empty())
7328 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007329 };
7330
7331 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007332 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007333 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007334
7335 llvm::Value *BasePointersArrayArg = nullptr;
7336 llvm::Value *PointersArrayArg = nullptr;
7337 llvm::Value *SizesArrayArg = nullptr;
7338 llvm::Value *MapTypesArrayArg = nullptr;
7339 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007340 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007341
7342 // Emit device ID if any.
7343 llvm::Value *DeviceID = nullptr;
7344 if (Device)
7345 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7346 CGF.Int32Ty, /*isSigned=*/true);
7347 else
7348 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7349
7350 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007351 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007352
7353 llvm::Value *OffloadingArgs[] = {
7354 DeviceID, PointerNum, BasePointersArrayArg,
7355 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7356 auto &RT = CGF.CGM.getOpenMPRuntime();
7357 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7358 OffloadingArgs);
7359 };
7360
Samuel Antaocc10b852016-07-28 14:23:26 +00007361 // If we need device pointer privatization, we need to emit the body of the
7362 // region with no privatization in the 'else' branch of the conditional.
7363 // Otherwise, we don't have to do anything.
7364 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7365 PrePostActionTy &) {
7366 if (!Info.CaptureDeviceAddrMap.empty()) {
7367 CodeGen.setAction(NoPrivAction);
7368 CodeGen(CGF);
7369 }
7370 };
7371
7372 // We don't have to do anything to close the region if the if clause evaluates
7373 // to false.
7374 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007375
7376 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007377 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007378 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007379 RegionCodeGenTy RCG(BeginThenGen);
7380 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007381 }
7382
Samuel Antaocc10b852016-07-28 14:23:26 +00007383 // If we don't require privatization of device pointers, we emit the body in
7384 // between the runtime calls. This avoids duplicating the body code.
7385 if (Info.CaptureDeviceAddrMap.empty()) {
7386 CodeGen.setAction(NoPrivAction);
7387 CodeGen(CGF);
7388 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007389
7390 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007391 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007392 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007393 RegionCodeGenTy RCG(EndThenGen);
7394 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007395 }
7396}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007397
Samuel Antao8d2d7302016-05-26 18:30:22 +00007398void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007399 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7400 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007401 if (!CGF.HaveInsertPoint())
7402 return;
7403
Samuel Antao8dd66282016-04-27 23:14:30 +00007404 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007405 isa<OMPTargetExitDataDirective>(D) ||
7406 isa<OMPTargetUpdateDirective>(D)) &&
7407 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007408
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007409 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007410 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007411 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007412 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007413 MappableExprsHandler::MapValuesArrayTy Pointers;
7414 MappableExprsHandler::MapValuesArrayTy Sizes;
7415 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7416
7417 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007418 MappableExprsHandler MEHandler(D, CGF);
7419 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007420
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007421 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007422 TargetDataInfo Info;
7423 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7424 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7425 Info.PointersArray, Info.SizesArray,
7426 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007427
7428 // Emit device ID if any.
7429 llvm::Value *DeviceID = nullptr;
7430 if (Device)
7431 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7432 CGF.Int32Ty, /*isSigned=*/true);
7433 else
7434 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7435
7436 // Emit the number of elements in the offloading arrays.
7437 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7438
7439 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007440 DeviceID, PointerNum, Info.BasePointersArray,
7441 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007442
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007443 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007444 // Select the right runtime function call for each expected standalone
7445 // directive.
7446 OpenMPRTLFunction RTLFn;
7447 switch (D.getDirectiveKind()) {
7448 default:
7449 llvm_unreachable("Unexpected standalone target data directive.");
7450 break;
7451 case OMPD_target_enter_data:
7452 RTLFn = OMPRTL__tgt_target_data_begin;
7453 break;
7454 case OMPD_target_exit_data:
7455 RTLFn = OMPRTL__tgt_target_data_end;
7456 break;
7457 case OMPD_target_update:
7458 RTLFn = OMPRTL__tgt_target_data_update;
7459 break;
7460 }
7461 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007462 };
7463
7464 // In the event we get an if clause, we don't have to take any action on the
7465 // else side.
7466 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7467
7468 if (IfCond) {
7469 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7470 } else {
7471 RegionCodeGenTy ThenGenRCG(ThenGen);
7472 ThenGenRCG(CGF);
7473 }
7474}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007475
7476namespace {
7477 /// Kind of parameter in a function with 'declare simd' directive.
7478 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7479 /// Attribute set of the parameter.
7480 struct ParamAttrTy {
7481 ParamKindTy Kind = Vector;
7482 llvm::APSInt StrideOrArg;
7483 llvm::APSInt Alignment;
7484 };
7485} // namespace
7486
7487static unsigned evaluateCDTSize(const FunctionDecl *FD,
7488 ArrayRef<ParamAttrTy> ParamAttrs) {
7489 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7490 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7491 // of that clause. The VLEN value must be power of 2.
7492 // In other case the notion of the function`s "characteristic data type" (CDT)
7493 // is used to compute the vector length.
7494 // CDT is defined in the following order:
7495 // a) For non-void function, the CDT is the return type.
7496 // b) If the function has any non-uniform, non-linear parameters, then the
7497 // CDT is the type of the first such parameter.
7498 // c) If the CDT determined by a) or b) above is struct, union, or class
7499 // type which is pass-by-value (except for the type that maps to the
7500 // built-in complex data type), the characteristic data type is int.
7501 // d) If none of the above three cases is applicable, the CDT is int.
7502 // The VLEN is then determined based on the CDT and the size of vector
7503 // register of that ISA for which current vector version is generated. The
7504 // VLEN is computed using the formula below:
7505 // VLEN = sizeof(vector_register) / sizeof(CDT),
7506 // where vector register size specified in section 3.2.1 Registers and the
7507 // Stack Frame of original AMD64 ABI document.
7508 QualType RetType = FD->getReturnType();
7509 if (RetType.isNull())
7510 return 0;
7511 ASTContext &C = FD->getASTContext();
7512 QualType CDT;
7513 if (!RetType.isNull() && !RetType->isVoidType())
7514 CDT = RetType;
7515 else {
7516 unsigned Offset = 0;
7517 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7518 if (ParamAttrs[Offset].Kind == Vector)
7519 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7520 ++Offset;
7521 }
7522 if (CDT.isNull()) {
7523 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7524 if (ParamAttrs[I + Offset].Kind == Vector) {
7525 CDT = FD->getParamDecl(I)->getType();
7526 break;
7527 }
7528 }
7529 }
7530 }
7531 if (CDT.isNull())
7532 CDT = C.IntTy;
7533 CDT = CDT->getCanonicalTypeUnqualified();
7534 if (CDT->isRecordType() || CDT->isUnionType())
7535 CDT = C.IntTy;
7536 return C.getTypeSize(CDT);
7537}
7538
7539static void
7540emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007541 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007542 ArrayRef<ParamAttrTy> ParamAttrs,
7543 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7544 struct ISADataTy {
7545 char ISA;
7546 unsigned VecRegSize;
7547 };
7548 ISADataTy ISAData[] = {
7549 {
7550 'b', 128
7551 }, // SSE
7552 {
7553 'c', 256
7554 }, // AVX
7555 {
7556 'd', 256
7557 }, // AVX2
7558 {
7559 'e', 512
7560 }, // AVX512
7561 };
7562 llvm::SmallVector<char, 2> Masked;
7563 switch (State) {
7564 case OMPDeclareSimdDeclAttr::BS_Undefined:
7565 Masked.push_back('N');
7566 Masked.push_back('M');
7567 break;
7568 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7569 Masked.push_back('N');
7570 break;
7571 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7572 Masked.push_back('M');
7573 break;
7574 }
7575 for (auto Mask : Masked) {
7576 for (auto &Data : ISAData) {
7577 SmallString<256> Buffer;
7578 llvm::raw_svector_ostream Out(Buffer);
7579 Out << "_ZGV" << Data.ISA << Mask;
7580 if (!VLENVal) {
7581 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7582 evaluateCDTSize(FD, ParamAttrs));
7583 } else
7584 Out << VLENVal;
7585 for (auto &ParamAttr : ParamAttrs) {
7586 switch (ParamAttr.Kind){
7587 case LinearWithVarStride:
7588 Out << 's' << ParamAttr.StrideOrArg;
7589 break;
7590 case Linear:
7591 Out << 'l';
7592 if (!!ParamAttr.StrideOrArg)
7593 Out << ParamAttr.StrideOrArg;
7594 break;
7595 case Uniform:
7596 Out << 'u';
7597 break;
7598 case Vector:
7599 Out << 'v';
7600 break;
7601 }
7602 if (!!ParamAttr.Alignment)
7603 Out << 'a' << ParamAttr.Alignment;
7604 }
7605 Out << '_' << Fn->getName();
7606 Fn->addFnAttr(Out.str());
7607 }
7608 }
7609}
7610
7611void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7612 llvm::Function *Fn) {
7613 ASTContext &C = CGM.getContext();
7614 FD = FD->getCanonicalDecl();
7615 // Map params to their positions in function decl.
7616 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7617 if (isa<CXXMethodDecl>(FD))
7618 ParamPositions.insert({FD, 0});
7619 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007620 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007621 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7622 ++ParamPos;
7623 }
7624 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7625 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7626 // Mark uniform parameters.
7627 for (auto *E : Attr->uniforms()) {
7628 E = E->IgnoreParenImpCasts();
7629 unsigned Pos;
7630 if (isa<CXXThisExpr>(E))
7631 Pos = ParamPositions[FD];
7632 else {
7633 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7634 ->getCanonicalDecl();
7635 Pos = ParamPositions[PVD];
7636 }
7637 ParamAttrs[Pos].Kind = Uniform;
7638 }
7639 // Get alignment info.
7640 auto NI = Attr->alignments_begin();
7641 for (auto *E : Attr->aligneds()) {
7642 E = E->IgnoreParenImpCasts();
7643 unsigned Pos;
7644 QualType ParmTy;
7645 if (isa<CXXThisExpr>(E)) {
7646 Pos = ParamPositions[FD];
7647 ParmTy = E->getType();
7648 } else {
7649 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7650 ->getCanonicalDecl();
7651 Pos = ParamPositions[PVD];
7652 ParmTy = PVD->getType();
7653 }
7654 ParamAttrs[Pos].Alignment =
7655 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7656 : llvm::APSInt::getUnsigned(
7657 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7658 .getQuantity());
7659 ++NI;
7660 }
7661 // Mark linear parameters.
7662 auto SI = Attr->steps_begin();
7663 auto MI = Attr->modifiers_begin();
7664 for (auto *E : Attr->linears()) {
7665 E = E->IgnoreParenImpCasts();
7666 unsigned Pos;
7667 if (isa<CXXThisExpr>(E))
7668 Pos = ParamPositions[FD];
7669 else {
7670 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7671 ->getCanonicalDecl();
7672 Pos = ParamPositions[PVD];
7673 }
7674 auto &ParamAttr = ParamAttrs[Pos];
7675 ParamAttr.Kind = Linear;
7676 if (*SI) {
7677 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7678 Expr::SE_AllowSideEffects)) {
7679 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7680 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7681 ParamAttr.Kind = LinearWithVarStride;
7682 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7683 ParamPositions[StridePVD->getCanonicalDecl()]);
7684 }
7685 }
7686 }
7687 }
7688 ++SI;
7689 ++MI;
7690 }
7691 llvm::APSInt VLENVal;
7692 if (const Expr *VLEN = Attr->getSimdlen())
7693 VLENVal = VLEN->EvaluateKnownConstInt(C);
7694 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7695 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7696 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7697 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7698 }
7699}
Alexey Bataev8b427062016-05-25 12:36:08 +00007700
7701namespace {
7702/// Cleanup action for doacross support.
7703class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7704public:
7705 static const int DoacrossFinArgs = 2;
7706
7707private:
7708 llvm::Value *RTLFn;
7709 llvm::Value *Args[DoacrossFinArgs];
7710
7711public:
7712 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7713 : RTLFn(RTLFn) {
7714 assert(CallArgs.size() == DoacrossFinArgs);
7715 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7716 }
7717 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7718 if (!CGF.HaveInsertPoint())
7719 return;
7720 CGF.EmitRuntimeCall(RTLFn, Args);
7721 }
7722};
7723} // namespace
7724
7725void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7726 const OMPLoopDirective &D) {
7727 if (!CGF.HaveInsertPoint())
7728 return;
7729
7730 ASTContext &C = CGM.getContext();
7731 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7732 RecordDecl *RD;
7733 if (KmpDimTy.isNull()) {
7734 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7735 // kmp_int64 lo; // lower
7736 // kmp_int64 up; // upper
7737 // kmp_int64 st; // stride
7738 // };
7739 RD = C.buildImplicitRecord("kmp_dim");
7740 RD->startDefinition();
7741 addFieldToRecordDecl(C, RD, Int64Ty);
7742 addFieldToRecordDecl(C, RD, Int64Ty);
7743 addFieldToRecordDecl(C, RD, Int64Ty);
7744 RD->completeDefinition();
7745 KmpDimTy = C.getRecordType(RD);
7746 } else
7747 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7748
7749 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7750 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7751 enum { LowerFD = 0, UpperFD, StrideFD };
7752 // Fill dims with data.
7753 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7754 // dims.upper = num_iterations;
7755 LValue UpperLVal =
7756 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7757 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7758 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7759 Int64Ty, D.getNumIterations()->getExprLoc());
7760 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7761 // dims.stride = 1;
7762 LValue StrideLVal =
7763 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7764 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7765 StrideLVal);
7766
7767 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7768 // kmp_int32 num_dims, struct kmp_dim * dims);
7769 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7770 getThreadID(CGF, D.getLocStart()),
7771 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7772 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7773 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7774
7775 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7776 CGF.EmitRuntimeCall(RTLFn, Args);
7777 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7778 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7779 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7780 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7781 llvm::makeArrayRef(FiniArgs));
7782}
7783
7784void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7785 const OMPDependClause *C) {
7786 QualType Int64Ty =
7787 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7788 const Expr *CounterVal = C->getCounterValue();
7789 assert(CounterVal);
7790 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7791 CounterVal->getType(), Int64Ty,
7792 CounterVal->getExprLoc());
7793 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7794 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7795 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7796 getThreadID(CGF, C->getLocStart()),
7797 CntAddr.getPointer()};
7798 llvm::Value *RTLFn;
7799 if (C->getDependencyKind() == OMPC_DEPEND_source)
7800 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7801 else {
7802 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7803 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7804 }
7805 CGF.EmitRuntimeCall(RTLFn, Args);
7806}
7807
Alexey Bataev3c595a62017-08-14 15:01:03 +00007808void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7809 ArrayRef<llvm::Value *> Args,
7810 SourceLocation Loc) const {
7811 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7812
7813 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007814 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007815 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007816 return;
7817 }
7818 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007819 CGF.EmitRuntimeCall(Callee, Args);
7820}
7821
7822void CGOpenMPRuntime::emitOutlinedFunctionCall(
7823 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7824 ArrayRef<llvm::Value *> Args) const {
7825 assert(Loc.isValid() && "Outlined function call location must be valid.");
7826 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007827}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007828
7829Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7830 const VarDecl *NativeParam,
7831 const VarDecl *TargetParam) const {
7832 return CGF.GetAddrOfLocalVar(NativeParam);
7833}