blob: 5db29eb6004d73a8ec02a72f141940f9ebf8ad76 [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 //
George Rokos63bc9d62017-11-21 18:25:12 +0000671 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
672 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000673 // *arg_types);
674 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000675 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
676 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
677 // *arg_types);
678 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000679 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
680 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
681 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000682 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000683 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
684 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
685 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
686 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000687 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
688 OMPRTL__tgt_register_lib,
689 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
690 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000691 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
692 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000693 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000694 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
695 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
696 // *arg_types);
697 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000698 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
699 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000700 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000701 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
702 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
703 // *arg_types);
704 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000705 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
706 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000707 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000708 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
709 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
710 // *arg_types);
711 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000712};
713
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000714/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
715/// region.
716class CleanupTy final : public EHScopeStack::Cleanup {
717 PrePostActionTy *Action;
718
719public:
720 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
721 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
722 if (!CGF.HaveInsertPoint())
723 return;
724 Action->Exit(CGF);
725 }
726};
727
Hans Wennborg7eb54642015-09-10 17:07:54 +0000728} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000729
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000730void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
731 CodeGenFunction::RunCleanupsScope Scope(CGF);
732 if (PrePostAction) {
733 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
734 Callback(CodeGen, CGF, *PrePostAction);
735 } else {
736 PrePostActionTy Action;
737 Callback(CodeGen, CGF, Action);
738 }
739}
740
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000741/// Check if the combiner is a call to UDR combiner and if it is so return the
742/// UDR decl used for reduction.
743static const OMPDeclareReductionDecl *
744getReductionInit(const Expr *ReductionOp) {
745 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
746 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
747 if (auto *DRE =
748 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
749 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
750 return DRD;
751 return nullptr;
752}
753
754static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
755 const OMPDeclareReductionDecl *DRD,
756 const Expr *InitOp,
757 Address Private, Address Original,
758 QualType Ty) {
759 if (DRD->getInitializer()) {
760 std::pair<llvm::Function *, llvm::Function *> Reduction =
761 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
762 auto *CE = cast<CallExpr>(InitOp);
763 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
764 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
765 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
766 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
767 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
768 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
769 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
770 [=]() -> Address { return Private; });
771 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
772 [=]() -> Address { return Original; });
773 (void)PrivateScope.Privatize();
774 RValue Func = RValue::get(Reduction.second);
775 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
776 CGF.EmitIgnoredExpr(InitOp);
777 } else {
778 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
779 auto *GV = new llvm::GlobalVariable(
780 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
781 llvm::GlobalValue::PrivateLinkage, Init, ".init");
782 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
783 RValue InitRVal;
784 switch (CGF.getEvaluationKind(Ty)) {
785 case TEK_Scalar:
786 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
787 break;
788 case TEK_Complex:
789 InitRVal =
790 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
791 break;
792 case TEK_Aggregate:
793 InitRVal = RValue::getAggregate(LV.getAddress());
794 break;
795 }
796 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
797 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
798 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
799 /*IsInitializer=*/false);
800 }
801}
802
803/// \brief Emit initialization of arrays of complex types.
804/// \param DestAddr Address of the array.
805/// \param Type Type of array.
806/// \param Init Initial expression of array.
807/// \param SrcAddr Address of the original array.
808static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000809 QualType Type, bool EmitDeclareReductionInit,
810 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000811 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000812 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000813 // Perform element-by-element initialization.
814 QualType ElementTy;
815
816 // Drill down to the base element type on both arrays.
817 auto ArrayTy = Type->getAsArrayTypeUnsafe();
818 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
819 DestAddr =
820 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
821 if (DRD)
822 SrcAddr =
823 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
824
825 llvm::Value *SrcBegin = nullptr;
826 if (DRD)
827 SrcBegin = SrcAddr.getPointer();
828 auto DestBegin = DestAddr.getPointer();
829 // Cast from pointer to array type to pointer to single element.
830 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
831 // The basic structure here is a while-do loop.
832 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
833 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
834 auto IsEmpty =
835 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
836 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
837
838 // Enter the loop body, making that address the current address.
839 auto EntryBB = CGF.Builder.GetInsertBlock();
840 CGF.EmitBlock(BodyBB);
841
842 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
843
844 llvm::PHINode *SrcElementPHI = nullptr;
845 Address SrcElementCurrent = Address::invalid();
846 if (DRD) {
847 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
848 "omp.arraycpy.srcElementPast");
849 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
850 SrcElementCurrent =
851 Address(SrcElementPHI,
852 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
853 }
854 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
855 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
856 DestElementPHI->addIncoming(DestBegin, EntryBB);
857 Address DestElementCurrent =
858 Address(DestElementPHI,
859 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
860
861 // Emit copy.
862 {
863 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000864 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000865 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
866 SrcElementCurrent, ElementTy);
867 } else
868 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
869 /*IsInitializer=*/false);
870 }
871
872 if (DRD) {
873 // Shift the address forward by one element.
874 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
875 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
876 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
877 }
878
879 // Shift the address forward by one element.
880 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
881 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
882 // Check whether we've reached the end.
883 auto Done =
884 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
885 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
886 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
887
888 // Done.
889 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
890}
891
892LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000893 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000894}
895
896LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
897 const Expr *E) {
898 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
899 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
900 return LValue();
901}
902
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000903void ReductionCodeGen::emitAggregateInitialization(
904 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
905 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000906 // Emit VarDecl with copy init for arrays.
907 // Get the address of the original variable captured in current
908 // captured region.
909 auto *PrivateVD =
910 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000911 bool EmitDeclareReductionInit =
912 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000913 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000914 EmitDeclareReductionInit,
915 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
916 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000917 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000918}
919
920ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
921 ArrayRef<const Expr *> Privates,
922 ArrayRef<const Expr *> ReductionOps) {
923 ClausesData.reserve(Shareds.size());
924 SharedAddresses.reserve(Shareds.size());
925 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000926 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000927 auto IPriv = Privates.begin();
928 auto IRed = ReductionOps.begin();
929 for (const auto *Ref : Shareds) {
930 ClausesData.emplace_back(Ref, *IPriv, *IRed);
931 std::advance(IPriv, 1);
932 std::advance(IRed, 1);
933 }
934}
935
936void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
937 assert(SharedAddresses.size() == N &&
938 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000939 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
940 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
941 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942}
943
944void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
945 auto *PrivateVD =
946 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
947 QualType PrivateType = PrivateVD->getType();
948 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000949 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000950 Sizes.emplace_back(
951 CGF.getTypeSize(
952 SharedAddresses[N].first.getType().getNonReferenceType()),
953 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 return;
955 }
956 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000957 llvm::Value *SizeInChars;
958 llvm::Type *ElemType =
959 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
960 ->getElementType();
961 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000962 if (AsArraySection) {
963 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
964 SharedAddresses[N].first.getPointer());
965 Size = CGF.Builder.CreateNUWAdd(
966 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000968 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000969 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000971 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000972 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000973 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000974 CodeGenFunction::OpaqueValueMapping OpaqueMap(
975 CGF,
976 cast<OpaqueValueExpr>(
977 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
978 RValue::get(Size));
979 CGF.EmitVariablyModifiedType(PrivateType);
980}
981
982void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
983 llvm::Value *Size) {
984 auto *PrivateVD =
985 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
986 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000987 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000988 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000989 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000990 "items.");
991 return;
992 }
993 CodeGenFunction::OpaqueValueMapping OpaqueMap(
994 CGF,
995 cast<OpaqueValueExpr>(
996 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
997 RValue::get(Size));
998 CGF.EmitVariablyModifiedType(PrivateType);
999}
1000
1001void ReductionCodeGen::emitInitialization(
1002 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1003 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1004 assert(SharedAddresses.size() > N && "No variable was generated");
1005 auto *PrivateVD =
1006 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1007 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1008 QualType PrivateType = PrivateVD->getType();
1009 PrivateAddr = CGF.Builder.CreateElementBitCast(
1010 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1011 QualType SharedType = SharedAddresses[N].first.getType();
1012 SharedLVal = CGF.MakeAddrLValue(
1013 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1014 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001015 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001016 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001017 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001018 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001019 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1020 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1021 PrivateAddr, SharedLVal.getAddress(),
1022 SharedLVal.getType());
1023 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1024 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1025 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1026 PrivateVD->getType().getQualifiers(),
1027 /*IsInitializer=*/false);
1028 }
1029}
1030
1031bool ReductionCodeGen::needCleanups(unsigned N) {
1032 auto *PrivateVD =
1033 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1034 QualType PrivateType = PrivateVD->getType();
1035 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1036 return DTorKind != QualType::DK_none;
1037}
1038
1039void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1040 Address PrivateAddr) {
1041 auto *PrivateVD =
1042 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1043 QualType PrivateType = PrivateVD->getType();
1044 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1045 if (needCleanups(N)) {
1046 PrivateAddr = CGF.Builder.CreateElementBitCast(
1047 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1048 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1049 }
1050}
1051
1052static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1053 LValue BaseLV) {
1054 BaseTy = BaseTy.getNonReferenceType();
1055 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1056 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1057 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1058 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1059 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001060 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1061 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001062 }
1063 BaseTy = BaseTy->getPointeeType();
1064 }
1065 return CGF.MakeAddrLValue(
1066 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1067 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001068 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001069 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001070}
1071
1072static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1073 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1074 llvm::Value *Addr) {
1075 Address Tmp = Address::invalid();
1076 Address TopTmp = Address::invalid();
1077 Address MostTopTmp = Address::invalid();
1078 BaseTy = BaseTy.getNonReferenceType();
1079 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1080 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1081 Tmp = CGF.CreateMemTemp(BaseTy);
1082 if (TopTmp.isValid())
1083 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1084 else
1085 MostTopTmp = Tmp;
1086 TopTmp = Tmp;
1087 BaseTy = BaseTy->getPointeeType();
1088 }
1089 llvm::Type *Ty = BaseLVType;
1090 if (Tmp.isValid())
1091 Ty = Tmp.getElementType();
1092 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1093 if (Tmp.isValid()) {
1094 CGF.Builder.CreateStore(Addr, Tmp);
1095 return MostTopTmp;
1096 }
1097 return Address(Addr, BaseLVAlignment);
1098}
1099
1100Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1101 Address PrivateAddr) {
1102 const DeclRefExpr *DE;
1103 const VarDecl *OrigVD = nullptr;
1104 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1105 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1106 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1107 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1108 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1109 Base = TempASE->getBase()->IgnoreParenImpCasts();
1110 DE = cast<DeclRefExpr>(Base);
1111 OrigVD = cast<VarDecl>(DE->getDecl());
1112 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1113 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1114 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1115 Base = TempASE->getBase()->IgnoreParenImpCasts();
1116 DE = cast<DeclRefExpr>(Base);
1117 OrigVD = cast<VarDecl>(DE->getDecl());
1118 }
1119 if (OrigVD) {
1120 BaseDecls.emplace_back(OrigVD);
1121 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1122 LValue BaseLValue =
1123 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1124 OriginalBaseLValue);
1125 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1126 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001127 llvm::Value *PrivatePointer =
1128 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1129 PrivateAddr.getPointer(),
1130 SharedAddresses[N].first.getAddress().getType());
1131 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001132 return castToBase(CGF, OrigVD->getType(),
1133 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001134 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 OriginalBaseLValue.getAlignment(), Ptr);
1136 }
1137 BaseDecls.emplace_back(
1138 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1139 return PrivateAddr;
1140}
1141
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001142bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1143 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1144 return DRD && DRD->getInitializer();
1145}
1146
Alexey Bataev18095712014-10-10 12:19:54 +00001147LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001148 return CGF.EmitLoadOfPointerLValue(
1149 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1150 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001151}
1152
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001153void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001154 if (!CGF.HaveInsertPoint())
1155 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001156 // 1.2.2 OpenMP Language Terminology
1157 // Structured block - An executable statement with a single entry at the
1158 // top and a single exit at the bottom.
1159 // The point of exit cannot be a branch out of the structured block.
1160 // longjmp() and throw() must not violate the entry/exit criteria.
1161 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001162 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001163 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001164}
1165
Alexey Bataev62b63b12015-03-10 07:28:44 +00001166LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1167 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001168 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1169 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001170 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001171}
1172
Alexey Bataev9959db52014-05-06 10:08:46 +00001173CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001174 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001175 IdentTy = llvm::StructType::create(
1176 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1177 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001178 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001179 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001180
1181 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001182}
1183
Alexey Bataev91797552015-03-18 04:13:55 +00001184void CGOpenMPRuntime::clear() {
1185 InternalVars.clear();
1186}
1187
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001188static llvm::Function *
1189emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1190 const Expr *CombinerInitializer, const VarDecl *In,
1191 const VarDecl *Out, bool IsCombiner) {
1192 // void .omp_combiner.(Ty *in, Ty *out);
1193 auto &C = CGM.getContext();
1194 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1195 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001196 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001197 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001198 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001199 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001200 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001201 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001202 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001203 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001204 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1205 auto *Fn = llvm::Function::Create(
1206 FnTy, llvm::GlobalValue::InternalLinkage,
1207 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1208 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001209 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001210 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001211 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001212 CodeGenFunction CGF(CGM);
1213 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1214 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1215 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1216 CodeGenFunction::OMPPrivateScope Scope(CGF);
1217 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1218 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1219 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1220 .getAddress();
1221 });
1222 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1223 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1224 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1225 .getAddress();
1226 });
1227 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001228 if (!IsCombiner && Out->hasInit() &&
1229 !CGF.isTrivialInitializer(Out->getInit())) {
1230 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1231 Out->getType().getQualifiers(),
1232 /*IsInitializer=*/true);
1233 }
1234 if (CombinerInitializer)
1235 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001236 Scope.ForceCleanup();
1237 CGF.FinishFunction();
1238 return Fn;
1239}
1240
1241void CGOpenMPRuntime::emitUserDefinedReduction(
1242 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1243 if (UDRMap.count(D) > 0)
1244 return;
1245 auto &C = CGM.getContext();
1246 if (!In || !Out) {
1247 In = &C.Idents.get("omp_in");
1248 Out = &C.Idents.get("omp_out");
1249 }
1250 llvm::Function *Combiner = emitCombinerOrInitializer(
1251 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1252 cast<VarDecl>(D->lookup(Out).front()),
1253 /*IsCombiner=*/true);
1254 llvm::Function *Initializer = nullptr;
1255 if (auto *Init = D->getInitializer()) {
1256 if (!Priv || !Orig) {
1257 Priv = &C.Idents.get("omp_priv");
1258 Orig = &C.Idents.get("omp_orig");
1259 }
1260 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001261 CGM, D->getType(),
1262 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1263 : nullptr,
1264 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001265 cast<VarDecl>(D->lookup(Priv).front()),
1266 /*IsCombiner=*/false);
1267 }
1268 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1269 if (CGF) {
1270 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1271 Decls.second.push_back(D);
1272 }
1273}
1274
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001275std::pair<llvm::Function *, llvm::Function *>
1276CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1277 auto I = UDRMap.find(D);
1278 if (I != UDRMap.end())
1279 return I->second;
1280 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1281 return UDRMap.lookup(D);
1282}
1283
John McCall7f416cc2015-09-08 08:05:57 +00001284// Layout information for ident_t.
1285static CharUnits getIdentAlign(CodeGenModule &CGM) {
1286 return CGM.getPointerAlign();
1287}
1288static CharUnits getIdentSize(CodeGenModule &CGM) {
1289 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1290 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1291}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001292static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001293 // All the fields except the last are i32, so this works beautifully.
1294 return unsigned(Field) * CharUnits::fromQuantity(4);
1295}
1296static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001297 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001298 const llvm::Twine &Name = "") {
1299 auto Offset = getOffsetOfIdentField(Field);
1300 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1301}
1302
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001303static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1304 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1305 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1306 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001307 assert(ThreadIDVar->getType()->isPointerType() &&
1308 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001309 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001310 bool HasCancel = false;
1311 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1312 HasCancel = OPD->hasCancel();
1313 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1314 HasCancel = OPSD->hasCancel();
1315 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1316 HasCancel = OPFD->hasCancel();
Alexey Bataev2139ed62017-11-16 18:20:21 +00001317 else if (auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1318 HasCancel = OPFD->hasCancel();
Alexey Bataev10a54312017-11-27 16:54:08 +00001319 else if (auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1320 HasCancel = OPFD->hasCancel();
1321 else if (auto *OPFD = dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1322 HasCancel = OPFD->hasCancel();
1323 else if (auto *OPFD =
1324 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1325 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001326 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001327 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001328 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001329 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001330}
1331
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001332llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1333 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1334 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1335 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1336 return emitParallelOrTeamsOutlinedFunction(
1337 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1338}
1339
1340llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1341 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1342 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1343 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1344 return emitParallelOrTeamsOutlinedFunction(
1345 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1346}
1347
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001348llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1349 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001350 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1351 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1352 bool Tied, unsigned &NumberOfParts) {
1353 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1354 PrePostActionTy &) {
1355 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1356 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1357 llvm::Value *TaskArgs[] = {
1358 UpLoc, ThreadID,
1359 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1360 TaskTVar->getType()->castAs<PointerType>())
1361 .getPointer()};
1362 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1363 };
1364 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1365 UntiedCodeGen);
1366 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001367 assert(!ThreadIDVar->getType()->isPointerType() &&
1368 "thread id variable must be of type kmp_int32 for tasks");
1369 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001370 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001371 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001372 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1373 InnermostKind,
1374 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001375 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001376 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1377 if (!Tied)
1378 NumberOfParts = Action.getNumberOfParts();
1379 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001380}
1381
Alexey Bataev50b3c952016-02-19 10:38:26 +00001382Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001383 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001384 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001385 if (!Entry) {
1386 if (!DefaultOpenMPPSource) {
1387 // Initialize default location for psource field of ident_t structure of
1388 // all ident_t objects. Format is ";file;function;line;column;;".
1389 // Taken from
1390 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1391 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001392 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001393 DefaultOpenMPPSource =
1394 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1395 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001396
John McCall23c9dc62016-11-28 22:18:27 +00001397 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001398 auto fields = builder.beginStruct(IdentTy);
1399 fields.addInt(CGM.Int32Ty, 0);
1400 fields.addInt(CGM.Int32Ty, Flags);
1401 fields.addInt(CGM.Int32Ty, 0);
1402 fields.addInt(CGM.Int32Ty, 0);
1403 fields.add(DefaultOpenMPPSource);
1404 auto DefaultOpenMPLocation =
1405 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1406 llvm::GlobalValue::PrivateLinkage);
1407 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1408
John McCall7f416cc2015-09-08 08:05:57 +00001409 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001410 }
John McCall7f416cc2015-09-08 08:05:57 +00001411 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001412}
1413
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001414llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1415 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001416 unsigned Flags) {
1417 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001418 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001419 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001420 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001421 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001422
1423 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1424
John McCall7f416cc2015-09-08 08:05:57 +00001425 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001426 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1427 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001428 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1429
Alexander Musmanc6388682014-12-15 07:07:06 +00001430 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1431 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001432 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001433 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001434 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1435 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001436 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001437 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001438 LocValue = AI;
1439
1440 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1441 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001442 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001443 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001444 }
1445
1446 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001447 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001448
Alexey Bataevf002aca2014-05-30 05:48:40 +00001449 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1450 if (OMPDebugLoc == nullptr) {
1451 SmallString<128> Buffer2;
1452 llvm::raw_svector_ostream OS2(Buffer2);
1453 // Build debug location
1454 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1455 OS2 << ";" << PLoc.getFilename() << ";";
1456 if (const FunctionDecl *FD =
1457 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1458 OS2 << FD->getQualifiedNameAsString();
1459 }
1460 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1461 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1462 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001463 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001464 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001465 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1466
John McCall7f416cc2015-09-08 08:05:57 +00001467 // Our callers always pass this to a runtime function, so for
1468 // convenience, go ahead and return a naked pointer.
1469 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001470}
1471
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001472llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1473 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001474 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1475
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001476 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001477 // Check whether we've already cached a load of the thread id in this
1478 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001479 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001480 if (I != OpenMPLocThreadIDMap.end()) {
1481 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001482 if (ThreadID != nullptr)
1483 return ThreadID;
1484 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001485 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001486 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1487 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001488 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001489 if (auto *OMPRegionInfo =
1490 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1491 if (OMPRegionInfo->getThreadIDVariable()) {
1492 // Check if this an outlined function with thread id passed as argument.
1493 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1494 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1495 // If value loaded in entry block, cache it and use it everywhere in
1496 // function.
1497 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1498 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1499 Elem.second.ThreadID = ThreadID;
1500 }
1501 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001502 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001503 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001504 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001505
1506 // This is not an outlined function region - need to call __kmpc_int32
1507 // kmpc_global_thread_num(ident_t *loc).
1508 // Generate thread id value and cache this value for use across the
1509 // function.
1510 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1511 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001512 auto *Call = CGF.Builder.CreateCall(
1513 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1514 emitUpdateLocation(CGF, Loc));
1515 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001516 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001517 Elem.second.ThreadID = Call;
1518 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001519}
1520
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001521void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001522 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001523 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1524 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001525 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1526 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1527 UDRMap.erase(D);
1528 }
1529 FunctionUDRMap.erase(CGF.CurFn);
1530 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001531}
1532
1533llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001534 if (!IdentTy) {
1535 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001536 return llvm::PointerType::getUnqual(IdentTy);
1537}
1538
1539llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001540 if (!Kmpc_MicroTy) {
1541 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1542 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1543 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1544 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1545 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001546 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1547}
1548
1549llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001550CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001551 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001552 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001553 case OMPRTL__kmpc_fork_call: {
1554 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1555 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001556 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1557 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001558 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001559 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001560 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1561 break;
1562 }
1563 case OMPRTL__kmpc_global_thread_num: {
1564 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001565 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001566 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001567 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001568 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1569 break;
1570 }
Alexey Bataev97720002014-11-11 04:05:39 +00001571 case OMPRTL__kmpc_threadprivate_cached: {
1572 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1573 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1574 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1575 CGM.VoidPtrTy, CGM.SizeTy,
1576 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1577 llvm::FunctionType *FnTy =
1578 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1579 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1580 break;
1581 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001582 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001583 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1584 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001585 llvm::Type *TypeParams[] = {
1586 getIdentTyPointerTy(), CGM.Int32Ty,
1587 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1588 llvm::FunctionType *FnTy =
1589 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1590 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1591 break;
1592 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001593 case OMPRTL__kmpc_critical_with_hint: {
1594 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1595 // kmp_critical_name *crit, uintptr_t hint);
1596 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1597 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1598 CGM.IntPtrTy};
1599 llvm::FunctionType *FnTy =
1600 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1602 break;
1603 }
Alexey Bataev97720002014-11-11 04:05:39 +00001604 case OMPRTL__kmpc_threadprivate_register: {
1605 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1606 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1607 // typedef void *(*kmpc_ctor)(void *);
1608 auto KmpcCtorTy =
1609 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1610 /*isVarArg*/ false)->getPointerTo();
1611 // typedef void *(*kmpc_cctor)(void *, void *);
1612 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1613 auto KmpcCopyCtorTy =
1614 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1615 /*isVarArg*/ false)->getPointerTo();
1616 // typedef void (*kmpc_dtor)(void *);
1617 auto KmpcDtorTy =
1618 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1619 ->getPointerTo();
1620 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1621 KmpcCopyCtorTy, KmpcDtorTy};
1622 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1623 /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1625 break;
1626 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001627 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001628 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1629 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001630 llvm::Type *TypeParams[] = {
1631 getIdentTyPointerTy(), CGM.Int32Ty,
1632 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1633 llvm::FunctionType *FnTy =
1634 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1635 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1636 break;
1637 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001638 case OMPRTL__kmpc_cancel_barrier: {
1639 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1640 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001641 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1642 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001643 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1644 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001645 break;
1646 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001647 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001648 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1650 llvm::FunctionType *FnTy =
1651 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1652 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1653 break;
1654 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001655 case OMPRTL__kmpc_for_static_fini: {
1656 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1657 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1658 llvm::FunctionType *FnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1660 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1661 break;
1662 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001663 case OMPRTL__kmpc_push_num_threads: {
1664 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1665 // kmp_int32 num_threads)
1666 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1667 CGM.Int32Ty};
1668 llvm::FunctionType *FnTy =
1669 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1670 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1671 break;
1672 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001673 case OMPRTL__kmpc_serialized_parallel: {
1674 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1675 // global_tid);
1676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1677 llvm::FunctionType *FnTy =
1678 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1679 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1680 break;
1681 }
1682 case OMPRTL__kmpc_end_serialized_parallel: {
1683 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1684 // global_tid);
1685 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1686 llvm::FunctionType *FnTy =
1687 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1688 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1689 break;
1690 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001691 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001692 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001693 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1694 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001695 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001696 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1697 break;
1698 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001699 case OMPRTL__kmpc_master: {
1700 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1701 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1702 llvm::FunctionType *FnTy =
1703 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1704 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1705 break;
1706 }
1707 case OMPRTL__kmpc_end_master: {
1708 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1709 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1710 llvm::FunctionType *FnTy =
1711 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1712 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1713 break;
1714 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001715 case OMPRTL__kmpc_omp_taskyield: {
1716 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1717 // int end_part);
1718 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1719 llvm::FunctionType *FnTy =
1720 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1721 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1722 break;
1723 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001724 case OMPRTL__kmpc_single: {
1725 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1726 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1727 llvm::FunctionType *FnTy =
1728 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1729 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1730 break;
1731 }
1732 case OMPRTL__kmpc_end_single: {
1733 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1734 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1735 llvm::FunctionType *FnTy =
1736 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1737 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1738 break;
1739 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001740 case OMPRTL__kmpc_omp_task_alloc: {
1741 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1742 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1743 // kmp_routine_entry_t *task_entry);
1744 assert(KmpRoutineEntryPtrTy != nullptr &&
1745 "Type kmp_routine_entry_t must be created.");
1746 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1747 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1748 // Return void * and then cast to particular kmp_task_t type.
1749 llvm::FunctionType *FnTy =
1750 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1751 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1752 break;
1753 }
1754 case OMPRTL__kmpc_omp_task: {
1755 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1756 // *new_task);
1757 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1758 CGM.VoidPtrTy};
1759 llvm::FunctionType *FnTy =
1760 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1762 break;
1763 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001764 case OMPRTL__kmpc_copyprivate: {
1765 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001766 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001767 // kmp_int32 didit);
1768 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1769 auto *CpyFnTy =
1770 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001771 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001772 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1773 CGM.Int32Ty};
1774 llvm::FunctionType *FnTy =
1775 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1776 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1777 break;
1778 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001779 case OMPRTL__kmpc_reduce: {
1780 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1781 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1782 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1783 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1784 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1785 /*isVarArg=*/false);
1786 llvm::Type *TypeParams[] = {
1787 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1788 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1789 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1790 llvm::FunctionType *FnTy =
1791 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1792 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1793 break;
1794 }
1795 case OMPRTL__kmpc_reduce_nowait: {
1796 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1797 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1798 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1799 // *lck);
1800 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1801 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1802 /*isVarArg=*/false);
1803 llvm::Type *TypeParams[] = {
1804 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1805 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1806 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1807 llvm::FunctionType *FnTy =
1808 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1809 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1810 break;
1811 }
1812 case OMPRTL__kmpc_end_reduce: {
1813 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1814 // kmp_critical_name *lck);
1815 llvm::Type *TypeParams[] = {
1816 getIdentTyPointerTy(), CGM.Int32Ty,
1817 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1818 llvm::FunctionType *FnTy =
1819 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1820 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1821 break;
1822 }
1823 case OMPRTL__kmpc_end_reduce_nowait: {
1824 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1825 // kmp_critical_name *lck);
1826 llvm::Type *TypeParams[] = {
1827 getIdentTyPointerTy(), CGM.Int32Ty,
1828 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1829 llvm::FunctionType *FnTy =
1830 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1831 RTLFn =
1832 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1833 break;
1834 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001835 case OMPRTL__kmpc_omp_task_begin_if0: {
1836 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1837 // *new_task);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1839 CGM.VoidPtrTy};
1840 llvm::FunctionType *FnTy =
1841 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1842 RTLFn =
1843 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1844 break;
1845 }
1846 case OMPRTL__kmpc_omp_task_complete_if0: {
1847 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1848 // *new_task);
1849 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1850 CGM.VoidPtrTy};
1851 llvm::FunctionType *FnTy =
1852 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1853 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1854 /*Name=*/"__kmpc_omp_task_complete_if0");
1855 break;
1856 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001857 case OMPRTL__kmpc_ordered: {
1858 // Build void __kmpc_ordered(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_ordered");
1863 break;
1864 }
1865 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001866 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001867 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1868 llvm::FunctionType *FnTy =
1869 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1870 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1871 break;
1872 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001873 case OMPRTL__kmpc_omp_taskwait: {
1874 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1875 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1876 llvm::FunctionType *FnTy =
1877 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1878 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1879 break;
1880 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001881 case OMPRTL__kmpc_taskgroup: {
1882 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1883 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1884 llvm::FunctionType *FnTy =
1885 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1886 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1887 break;
1888 }
1889 case OMPRTL__kmpc_end_taskgroup: {
1890 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1891 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1892 llvm::FunctionType *FnTy =
1893 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1894 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1895 break;
1896 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001897 case OMPRTL__kmpc_push_proc_bind: {
1898 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1899 // int proc_bind)
1900 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1901 llvm::FunctionType *FnTy =
1902 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1903 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1904 break;
1905 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001906 case OMPRTL__kmpc_omp_task_with_deps: {
1907 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1908 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1909 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1910 llvm::Type *TypeParams[] = {
1911 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1912 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1913 llvm::FunctionType *FnTy =
1914 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1915 RTLFn =
1916 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1917 break;
1918 }
1919 case OMPRTL__kmpc_omp_wait_deps: {
1920 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1921 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1922 // kmp_depend_info_t *noalias_dep_list);
1923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1924 CGM.Int32Ty, CGM.VoidPtrTy,
1925 CGM.Int32Ty, CGM.VoidPtrTy};
1926 llvm::FunctionType *FnTy =
1927 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1928 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1929 break;
1930 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001931 case OMPRTL__kmpc_cancellationpoint: {
1932 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1933 // global_tid, kmp_int32 cncl_kind)
1934 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1935 llvm::FunctionType *FnTy =
1936 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1937 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1938 break;
1939 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001940 case OMPRTL__kmpc_cancel: {
1941 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1942 // kmp_int32 cncl_kind)
1943 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1944 llvm::FunctionType *FnTy =
1945 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1946 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1947 break;
1948 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001949 case OMPRTL__kmpc_push_num_teams: {
1950 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1951 // kmp_int32 num_teams, kmp_int32 num_threads)
1952 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1953 CGM.Int32Ty};
1954 llvm::FunctionType *FnTy =
1955 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1956 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1957 break;
1958 }
1959 case OMPRTL__kmpc_fork_teams: {
1960 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1961 // microtask, ...);
1962 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1963 getKmpc_MicroPointerTy()};
1964 llvm::FunctionType *FnTy =
1965 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1966 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1967 break;
1968 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001969 case OMPRTL__kmpc_taskloop: {
1970 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1971 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1972 // sched, kmp_uint64 grainsize, void *task_dup);
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1974 CGM.IntTy,
1975 CGM.VoidPtrTy,
1976 CGM.IntTy,
1977 CGM.Int64Ty->getPointerTo(),
1978 CGM.Int64Ty->getPointerTo(),
1979 CGM.Int64Ty,
1980 CGM.IntTy,
1981 CGM.IntTy,
1982 CGM.Int64Ty,
1983 CGM.VoidPtrTy};
1984 llvm::FunctionType *FnTy =
1985 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1986 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1987 break;
1988 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001989 case OMPRTL__kmpc_doacross_init: {
1990 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1991 // num_dims, struct kmp_dim *dims);
1992 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1993 CGM.Int32Ty,
1994 CGM.Int32Ty,
1995 CGM.VoidPtrTy};
1996 llvm::FunctionType *FnTy =
1997 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1998 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1999 break;
2000 }
2001 case OMPRTL__kmpc_doacross_fini: {
2002 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2003 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2004 llvm::FunctionType *FnTy =
2005 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2006 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2007 break;
2008 }
2009 case OMPRTL__kmpc_doacross_post: {
2010 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2011 // *vec);
2012 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2013 CGM.Int64Ty->getPointerTo()};
2014 llvm::FunctionType *FnTy =
2015 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2016 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2017 break;
2018 }
2019 case OMPRTL__kmpc_doacross_wait: {
2020 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2021 // *vec);
2022 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2023 CGM.Int64Ty->getPointerTo()};
2024 llvm::FunctionType *FnTy =
2025 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2026 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2027 break;
2028 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002029 case OMPRTL__kmpc_task_reduction_init: {
2030 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2031 // *data);
2032 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2033 llvm::FunctionType *FnTy =
2034 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2035 RTLFn =
2036 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2037 break;
2038 }
2039 case OMPRTL__kmpc_task_reduction_get_th_data: {
2040 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2041 // *d);
2042 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2043 llvm::FunctionType *FnTy =
2044 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2045 RTLFn = CGM.CreateRuntimeFunction(
2046 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2047 break;
2048 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002049 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002050 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2051 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002052 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002053 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002054 CGM.VoidPtrTy,
2055 CGM.Int32Ty,
2056 CGM.VoidPtrPtrTy,
2057 CGM.VoidPtrPtrTy,
2058 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002059 CGM.Int64Ty->getPointerTo()};
Samuel Antaobed3c462015-10-02 16:14:20 +00002060 llvm::FunctionType *FnTy =
2061 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2062 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2063 break;
2064 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002065 case OMPRTL__tgt_target_nowait: {
2066 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2067 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2068 // int64_t *arg_types);
2069 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2070 CGM.VoidPtrTy,
2071 CGM.Int32Ty,
2072 CGM.VoidPtrPtrTy,
2073 CGM.VoidPtrPtrTy,
2074 CGM.SizeTy->getPointerTo(),
2075 CGM.Int64Ty->getPointerTo()};
2076 llvm::FunctionType *FnTy =
2077 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2078 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2079 break;
2080 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002081 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002082 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002083 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002084 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2085 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002086 CGM.VoidPtrTy,
2087 CGM.Int32Ty,
2088 CGM.VoidPtrPtrTy,
2089 CGM.VoidPtrPtrTy,
2090 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002091 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002092 CGM.Int32Ty,
2093 CGM.Int32Ty};
2094 llvm::FunctionType *FnTy =
2095 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2096 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2097 break;
2098 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002099 case OMPRTL__tgt_target_teams_nowait: {
2100 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2101 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2102 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2103 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2104 CGM.VoidPtrTy,
2105 CGM.Int32Ty,
2106 CGM.VoidPtrPtrTy,
2107 CGM.VoidPtrPtrTy,
2108 CGM.SizeTy->getPointerTo(),
2109 CGM.Int64Ty->getPointerTo(),
2110 CGM.Int32Ty,
2111 CGM.Int32Ty};
2112 llvm::FunctionType *FnTy =
2113 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2114 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2115 break;
2116 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002117 case OMPRTL__tgt_register_lib: {
2118 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2119 QualType ParamTy =
2120 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2121 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2122 llvm::FunctionType *FnTy =
2123 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2124 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2125 break;
2126 }
2127 case OMPRTL__tgt_unregister_lib: {
2128 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2129 QualType ParamTy =
2130 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2131 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2132 llvm::FunctionType *FnTy =
2133 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2134 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2135 break;
2136 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002137 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002138 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2139 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2140 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002141 CGM.Int32Ty,
2142 CGM.VoidPtrPtrTy,
2143 CGM.VoidPtrPtrTy,
2144 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002145 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002146 llvm::FunctionType *FnTy =
2147 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2148 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2149 break;
2150 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002151 case OMPRTL__tgt_target_data_begin_nowait: {
2152 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2153 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2154 // *arg_types);
2155 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2156 CGM.Int32Ty,
2157 CGM.VoidPtrPtrTy,
2158 CGM.VoidPtrPtrTy,
2159 CGM.SizeTy->getPointerTo(),
2160 CGM.Int64Ty->getPointerTo()};
2161 auto *FnTy =
2162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2163 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2164 break;
2165 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002166 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002167 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2168 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2169 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002170 CGM.Int32Ty,
2171 CGM.VoidPtrPtrTy,
2172 CGM.VoidPtrPtrTy,
2173 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002174 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002175 llvm::FunctionType *FnTy =
2176 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2177 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2178 break;
2179 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002180 case OMPRTL__tgt_target_data_end_nowait: {
2181 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2182 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2183 // *arg_types);
2184 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2185 CGM.Int32Ty,
2186 CGM.VoidPtrPtrTy,
2187 CGM.VoidPtrPtrTy,
2188 CGM.SizeTy->getPointerTo(),
2189 CGM.Int64Ty->getPointerTo()};
2190 auto *FnTy =
2191 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2192 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2193 break;
2194 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002195 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002196 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2197 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2198 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002199 CGM.Int32Ty,
2200 CGM.VoidPtrPtrTy,
2201 CGM.VoidPtrPtrTy,
2202 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002203 CGM.Int64Ty->getPointerTo()};
Samuel Antao8d2d7302016-05-26 18:30:22 +00002204 llvm::FunctionType *FnTy =
2205 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2206 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2207 break;
2208 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002209 case OMPRTL__tgt_target_data_update_nowait: {
2210 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2211 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2212 // *arg_types);
2213 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2214 CGM.Int32Ty,
2215 CGM.VoidPtrPtrTy,
2216 CGM.VoidPtrPtrTy,
2217 CGM.SizeTy->getPointerTo(),
2218 CGM.Int64Ty->getPointerTo()};
2219 auto *FnTy =
2220 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2221 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2222 break;
2223 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002224 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002225 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002226 return RTLFn;
2227}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002228
Alexander Musman21212e42015-03-13 10:38:23 +00002229llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2230 bool IVSigned) {
2231 assert((IVSize == 32 || IVSize == 64) &&
2232 "IV size is not compatible with the omp runtime");
2233 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2234 : "__kmpc_for_static_init_4u")
2235 : (IVSigned ? "__kmpc_for_static_init_8"
2236 : "__kmpc_for_static_init_8u");
2237 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2238 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2239 llvm::Type *TypeParams[] = {
2240 getIdentTyPointerTy(), // loc
2241 CGM.Int32Ty, // tid
2242 CGM.Int32Ty, // schedtype
2243 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2244 PtrTy, // p_lower
2245 PtrTy, // p_upper
2246 PtrTy, // p_stride
2247 ITy, // incr
2248 ITy // chunk
2249 };
2250 llvm::FunctionType *FnTy =
2251 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2252 return CGM.CreateRuntimeFunction(FnTy, Name);
2253}
2254
Alexander Musman92bdaab2015-03-12 13:37:50 +00002255llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2256 bool IVSigned) {
2257 assert((IVSize == 32 || IVSize == 64) &&
2258 "IV size is not compatible with the omp runtime");
2259 auto Name =
2260 IVSize == 32
2261 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2262 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2263 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2264 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2265 CGM.Int32Ty, // tid
2266 CGM.Int32Ty, // schedtype
2267 ITy, // lower
2268 ITy, // upper
2269 ITy, // stride
2270 ITy // chunk
2271 };
2272 llvm::FunctionType *FnTy =
2273 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2274 return CGM.CreateRuntimeFunction(FnTy, Name);
2275}
2276
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002277llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2278 bool IVSigned) {
2279 assert((IVSize == 32 || IVSize == 64) &&
2280 "IV size is not compatible with the omp runtime");
2281 auto Name =
2282 IVSize == 32
2283 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2284 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2285 llvm::Type *TypeParams[] = {
2286 getIdentTyPointerTy(), // loc
2287 CGM.Int32Ty, // tid
2288 };
2289 llvm::FunctionType *FnTy =
2290 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2291 return CGM.CreateRuntimeFunction(FnTy, Name);
2292}
2293
Alexander Musman92bdaab2015-03-12 13:37:50 +00002294llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2295 bool IVSigned) {
2296 assert((IVSize == 32 || IVSize == 64) &&
2297 "IV size is not compatible with the omp runtime");
2298 auto Name =
2299 IVSize == 32
2300 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2301 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2302 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2303 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2304 llvm::Type *TypeParams[] = {
2305 getIdentTyPointerTy(), // loc
2306 CGM.Int32Ty, // tid
2307 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2308 PtrTy, // p_lower
2309 PtrTy, // p_upper
2310 PtrTy // p_stride
2311 };
2312 llvm::FunctionType *FnTy =
2313 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2314 return CGM.CreateRuntimeFunction(FnTy, Name);
2315}
2316
Alexey Bataev97720002014-11-11 04:05:39 +00002317llvm::Constant *
2318CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002319 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2320 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002321 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002322 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002323 Twine(CGM.getMangledName(VD)) + ".cache.");
2324}
2325
John McCall7f416cc2015-09-08 08:05:57 +00002326Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2327 const VarDecl *VD,
2328 Address VDAddr,
2329 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002330 if (CGM.getLangOpts().OpenMPUseTLS &&
2331 CGM.getContext().getTargetInfo().isTLSSupported())
2332 return VDAddr;
2333
John McCall7f416cc2015-09-08 08:05:57 +00002334 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002335 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002336 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2337 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002338 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2339 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002340 return Address(CGF.EmitRuntimeCall(
2341 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2342 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002343}
2344
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002345void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002346 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002347 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2348 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2349 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002350 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2351 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002352 OMPLoc);
2353 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2354 // to register constructor/destructor for variable.
2355 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002356 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2357 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002358 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002359 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002360 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002361}
2362
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002363llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002364 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002365 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002366 if (CGM.getLangOpts().OpenMPUseTLS &&
2367 CGM.getContext().getTargetInfo().isTLSSupported())
2368 return nullptr;
2369
Alexey Bataev97720002014-11-11 04:05:39 +00002370 VD = VD->getDefinition(CGM.getContext());
2371 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2372 ThreadPrivateWithDefinition.insert(VD);
2373 QualType ASTTy = VD->getType();
2374
2375 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2376 auto Init = VD->getAnyInitializer();
2377 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2378 // Generate function that re-emits the declaration's initializer into the
2379 // threadprivate copy of the variable VD
2380 CodeGenFunction CtorCGF(CGM);
2381 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002382 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2383 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002384 Args.push_back(&Dst);
2385
John McCallc56a8b32016-03-11 04:30:31 +00002386 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2387 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002388 auto FTy = CGM.getTypes().GetFunctionType(FI);
2389 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002390 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002391 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2392 Args, SourceLocation());
2393 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002394 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002395 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002396 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2397 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2398 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002399 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2400 /*IsInitializer=*/true);
2401 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002402 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002403 CGM.getContext().VoidPtrTy, Dst.getLocation());
2404 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2405 CtorCGF.FinishFunction();
2406 Ctor = Fn;
2407 }
2408 if (VD->getType().isDestructedType() != QualType::DK_none) {
2409 // Generate function that emits destructor call for the threadprivate copy
2410 // of the variable VD
2411 CodeGenFunction DtorCGF(CGM);
2412 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002413 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2414 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002415 Args.push_back(&Dst);
2416
John McCallc56a8b32016-03-11 04:30:31 +00002417 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2418 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002419 auto FTy = CGM.getTypes().GetFunctionType(FI);
2420 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002421 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002422 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002423 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2424 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002425 // Create a scope with an artificial location for the body of this function.
2426 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002427 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2428 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002429 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2430 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002431 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2432 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2433 DtorCGF.FinishFunction();
2434 Dtor = Fn;
2435 }
2436 // Do not emit init function if it is not required.
2437 if (!Ctor && !Dtor)
2438 return nullptr;
2439
2440 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2441 auto CopyCtorTy =
2442 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2443 /*isVarArg=*/false)->getPointerTo();
2444 // Copying constructor for the threadprivate variable.
2445 // Must be NULL - reserved by runtime, but currently it requires that this
2446 // parameter is always NULL. Otherwise it fires assertion.
2447 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2448 if (Ctor == nullptr) {
2449 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2450 /*isVarArg=*/false)->getPointerTo();
2451 Ctor = llvm::Constant::getNullValue(CtorTy);
2452 }
2453 if (Dtor == nullptr) {
2454 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2455 /*isVarArg=*/false)->getPointerTo();
2456 Dtor = llvm::Constant::getNullValue(DtorTy);
2457 }
2458 if (!CGF) {
2459 auto InitFunctionTy =
2460 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2461 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002462 InitFunctionTy, ".__omp_threadprivate_init_.",
2463 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002464 CodeGenFunction InitCGF(CGM);
2465 FunctionArgList ArgList;
2466 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2467 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2468 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002469 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002470 InitCGF.FinishFunction();
2471 return InitFunction;
2472 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002473 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002474 }
2475 return nullptr;
2476}
2477
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002478Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2479 QualType VarType,
2480 StringRef Name) {
2481 llvm::Twine VarName(Name, ".artificial.");
2482 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2483 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2484 llvm::Value *Args[] = {
2485 emitUpdateLocation(CGF, SourceLocation()),
2486 getThreadID(CGF, SourceLocation()),
2487 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2488 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2489 /*IsSigned=*/false),
2490 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2491 return Address(
2492 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2493 CGF.EmitRuntimeCall(
2494 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2495 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2496 CGM.getPointerAlign());
2497}
2498
Alexey Bataev1d677132015-04-22 13:57:31 +00002499/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2500/// function. Here is the logic:
2501/// if (Cond) {
2502/// ThenGen();
2503/// } else {
2504/// ElseGen();
2505/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002506void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2507 const RegionCodeGenTy &ThenGen,
2508 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002509 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2510
2511 // If the condition constant folds and can be elided, try to avoid emitting
2512 // the condition and the dead arm of the if/else.
2513 bool CondConstant;
2514 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002515 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002516 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002517 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002518 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002519 return;
2520 }
2521
2522 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2523 // emit the conditional branch.
2524 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2525 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2526 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2527 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2528
2529 // Emit the 'then' code.
2530 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002531 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002532 CGF.EmitBranch(ContBlock);
2533 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002534 // There is no need to emit line number for unconditional branch.
2535 (void)ApplyDebugLocation::CreateEmpty(CGF);
2536 CGF.EmitBlock(ElseBlock);
2537 ElseGen(CGF);
2538 // There is no need to emit line number for unconditional branch.
2539 (void)ApplyDebugLocation::CreateEmpty(CGF);
2540 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002541 // Emit the continuation block for code after the if.
2542 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002543}
2544
Alexey Bataev1d677132015-04-22 13:57:31 +00002545void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2546 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002547 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002548 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002549 if (!CGF.HaveInsertPoint())
2550 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002551 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002552 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2553 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002554 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002555 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002556 llvm::Value *Args[] = {
2557 RTLoc,
2558 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002559 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002560 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2561 RealArgs.append(std::begin(Args), std::end(Args));
2562 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2563
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002564 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002565 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2566 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002567 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2568 PrePostActionTy &) {
2569 auto &RT = CGF.CGM.getOpenMPRuntime();
2570 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002571 // Build calls:
2572 // __kmpc_serialized_parallel(&Loc, GTid);
2573 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002574 CGF.EmitRuntimeCall(
2575 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002576
Alexey Bataev1d677132015-04-22 13:57:31 +00002577 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002578 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002579 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002580 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2581 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002582 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002583 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2584 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2585 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2586 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002587 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002588
Alexey Bataev1d677132015-04-22 13:57:31 +00002589 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002590 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002591 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002592 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2593 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002594 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002595 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002596 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002597 else {
2598 RegionCodeGenTy ThenRCG(ThenGen);
2599 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002600 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002601}
2602
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002603// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002604// thread-ID variable (it is passed in a first argument of the outlined function
2605// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2606// regular serial code region, get thread ID by calling kmp_int32
2607// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2608// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002609Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2610 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002611 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002612 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002613 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002614 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002615
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002616 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002617 auto Int32Ty =
2618 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2619 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2620 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002621 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002622
2623 return ThreadIDTemp;
2624}
2625
Alexey Bataev97720002014-11-11 04:05:39 +00002626llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002627CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002628 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002629 SmallString<256> Buffer;
2630 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002631 Out << Name;
2632 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002633 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2634 if (Elem.second) {
2635 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002636 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002637 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002638 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002639
David Blaikie13156b62014-11-19 03:06:06 +00002640 return Elem.second = new llvm::GlobalVariable(
2641 CGM.getModule(), Ty, /*IsConstant*/ false,
2642 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2643 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002644}
2645
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002646llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002647 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002648 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002649}
2650
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002651namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002652/// Common pre(post)-action for different OpenMP constructs.
2653class CommonActionTy final : public PrePostActionTy {
2654 llvm::Value *EnterCallee;
2655 ArrayRef<llvm::Value *> EnterArgs;
2656 llvm::Value *ExitCallee;
2657 ArrayRef<llvm::Value *> ExitArgs;
2658 bool Conditional;
2659 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002660
2661public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002662 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2663 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2664 bool Conditional = false)
2665 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2666 ExitArgs(ExitArgs), Conditional(Conditional) {}
2667 void Enter(CodeGenFunction &CGF) override {
2668 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2669 if (Conditional) {
2670 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2671 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2672 ContBlock = CGF.createBasicBlock("omp_if.end");
2673 // Generate the branch (If-stmt)
2674 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2675 CGF.EmitBlock(ThenBlock);
2676 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002677 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002678 void Done(CodeGenFunction &CGF) {
2679 // Emit the rest of blocks/branches
2680 CGF.EmitBranch(ContBlock);
2681 CGF.EmitBlock(ContBlock, true);
2682 }
2683 void Exit(CodeGenFunction &CGF) override {
2684 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002685 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002686};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002687} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002688
2689void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2690 StringRef CriticalName,
2691 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002692 SourceLocation Loc, const Expr *Hint) {
2693 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002694 // CriticalOpGen();
2695 // __kmpc_end_critical(ident_t *, gtid, Lock);
2696 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002697 if (!CGF.HaveInsertPoint())
2698 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002699 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2700 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002701 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2702 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002703 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002704 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2705 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2706 }
2707 CommonActionTy Action(
2708 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2709 : OMPRTL__kmpc_critical),
2710 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2711 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002712 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002713}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002714
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002715void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002716 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002717 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002718 if (!CGF.HaveInsertPoint())
2719 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002720 // if(__kmpc_master(ident_t *, gtid)) {
2721 // MasterOpGen();
2722 // __kmpc_end_master(ident_t *, gtid);
2723 // }
2724 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002725 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002726 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2727 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2728 /*Conditional=*/true);
2729 MasterOpGen.setAction(Action);
2730 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2731 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002732}
2733
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002734void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2735 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002736 if (!CGF.HaveInsertPoint())
2737 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002738 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2739 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002740 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002741 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002742 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002743 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2744 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002745}
2746
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002747void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2748 const RegionCodeGenTy &TaskgroupOpGen,
2749 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002750 if (!CGF.HaveInsertPoint())
2751 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002752 // __kmpc_taskgroup(ident_t *, gtid);
2753 // TaskgroupOpGen();
2754 // __kmpc_end_taskgroup(ident_t *, gtid);
2755 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002756 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2757 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2758 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2759 Args);
2760 TaskgroupOpGen.setAction(Action);
2761 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002762}
2763
John McCall7f416cc2015-09-08 08:05:57 +00002764/// Given an array of pointers to variables, project the address of a
2765/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002766static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2767 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002768 // Pull out the pointer to the variable.
2769 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002770 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002771 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2772
2773 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002774 Addr = CGF.Builder.CreateElementBitCast(
2775 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002776 return Addr;
2777}
2778
Alexey Bataeva63048e2015-03-23 06:18:07 +00002779static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002780 CodeGenModule &CGM, llvm::Type *ArgsType,
2781 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2782 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002783 auto &C = CGM.getContext();
2784 // void copy_func(void *LHSArg, void *RHSArg);
2785 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002786 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2787 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002788 Args.push_back(&LHSArg);
2789 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002790 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002791 auto *Fn = llvm::Function::Create(
2792 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2793 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002794 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002795 CodeGenFunction CGF(CGM);
2796 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002797 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002798 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002799 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2800 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2801 ArgsType), CGF.getPointerAlign());
2802 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2803 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2804 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002805 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2806 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2807 // ...
2808 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002809 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002810 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2811 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2812
2813 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2814 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2815
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002816 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2817 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002818 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002819 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002820 CGF.FinishFunction();
2821 return Fn;
2822}
2823
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002824void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002825 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002826 SourceLocation Loc,
2827 ArrayRef<const Expr *> CopyprivateVars,
2828 ArrayRef<const Expr *> SrcExprs,
2829 ArrayRef<const Expr *> DstExprs,
2830 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002831 if (!CGF.HaveInsertPoint())
2832 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002833 assert(CopyprivateVars.size() == SrcExprs.size() &&
2834 CopyprivateVars.size() == DstExprs.size() &&
2835 CopyprivateVars.size() == AssignmentOps.size());
2836 auto &C = CGM.getContext();
2837 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002838 // if(__kmpc_single(ident_t *, gtid)) {
2839 // SingleOpGen();
2840 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002841 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002842 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002843 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2844 // <copy_func>, did_it);
2845
John McCall7f416cc2015-09-08 08:05:57 +00002846 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002847 if (!CopyprivateVars.empty()) {
2848 // int32 did_it = 0;
2849 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2850 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002851 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002852 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002853 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002854 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002855 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2856 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2857 /*Conditional=*/true);
2858 SingleOpGen.setAction(Action);
2859 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2860 if (DidIt.isValid()) {
2861 // did_it = 1;
2862 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2863 }
2864 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002865 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2866 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002867 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002868 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2869 auto CopyprivateArrayTy =
2870 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2871 /*IndexTypeQuals=*/0);
2872 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002873 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002874 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2875 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002876 Address Elem = CGF.Builder.CreateConstArrayGEP(
2877 CopyprivateList, I, CGF.getPointerSize());
2878 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002879 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002880 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2881 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002882 }
2883 // Build function that copies private values from single region to all other
2884 // threads in the corresponding parallel region.
2885 auto *CpyFn = emitCopyprivateCopyFunction(
2886 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002887 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002888 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002889 Address CL =
2890 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2891 CGF.VoidPtrTy);
2892 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002893 llvm::Value *Args[] = {
2894 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2895 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002896 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002897 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002898 CpyFn, // void (*) (void *, void *) <copy_func>
2899 DidItVal // i32 did_it
2900 };
2901 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2902 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002903}
2904
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002905void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2906 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002907 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002908 if (!CGF.HaveInsertPoint())
2909 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002910 // __kmpc_ordered(ident_t *, gtid);
2911 // OrderedOpGen();
2912 // __kmpc_end_ordered(ident_t *, gtid);
2913 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002914 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002915 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002916 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2917 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2918 Args);
2919 OrderedOpGen.setAction(Action);
2920 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2921 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002922 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002923 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002924}
2925
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002926void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002927 OpenMPDirectiveKind Kind, bool EmitChecks,
2928 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002929 if (!CGF.HaveInsertPoint())
2930 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002931 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002932 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002933 unsigned Flags;
2934 if (Kind == OMPD_for)
2935 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2936 else if (Kind == OMPD_sections)
2937 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2938 else if (Kind == OMPD_single)
2939 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2940 else if (Kind == OMPD_barrier)
2941 Flags = OMP_IDENT_BARRIER_EXPL;
2942 else
2943 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002944 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2945 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002946 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2947 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002948 if (auto *OMPRegionInfo =
2949 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002950 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002951 auto *Result = CGF.EmitRuntimeCall(
2952 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002953 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002954 // if (__kmpc_cancel_barrier()) {
2955 // exit from construct;
2956 // }
2957 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2958 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2959 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2960 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2961 CGF.EmitBlock(ExitBB);
2962 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002963 auto CancelDestination =
2964 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002965 CGF.EmitBranchThroughCleanup(CancelDestination);
2966 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2967 }
2968 return;
2969 }
2970 }
2971 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002972}
2973
Alexander Musmanc6388682014-12-15 07:07:06 +00002974/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2975static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002976 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002977 switch (ScheduleKind) {
2978 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002979 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2980 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002981 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002982 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002983 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002984 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002985 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002986 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2987 case OMPC_SCHEDULE_auto:
2988 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002989 case OMPC_SCHEDULE_unknown:
2990 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002991 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002992 }
2993 llvm_unreachable("Unexpected runtime schedule");
2994}
2995
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002996/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2997static OpenMPSchedType
2998getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2999 // only static is allowed for dist_schedule
3000 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3001}
3002
Alexander Musmanc6388682014-12-15 07:07:06 +00003003bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3004 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003005 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003006 return Schedule == OMP_sch_static;
3007}
3008
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003009bool CGOpenMPRuntime::isStaticNonchunked(
3010 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3011 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3012 return Schedule == OMP_dist_sch_static;
3013}
3014
3015
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003016bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003017 auto Schedule =
3018 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003019 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3020 return Schedule != OMP_sch_static;
3021}
3022
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003023static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3024 OpenMPScheduleClauseModifier M1,
3025 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003026 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003027 switch (M1) {
3028 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003029 Modifier = OMP_sch_modifier_monotonic;
3030 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003031 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003032 Modifier = OMP_sch_modifier_nonmonotonic;
3033 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003034 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003035 if (Schedule == OMP_sch_static_chunked)
3036 Schedule = OMP_sch_static_balanced_chunked;
3037 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003038 case OMPC_SCHEDULE_MODIFIER_last:
3039 case OMPC_SCHEDULE_MODIFIER_unknown:
3040 break;
3041 }
3042 switch (M2) {
3043 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003044 Modifier = OMP_sch_modifier_monotonic;
3045 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003046 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003047 Modifier = OMP_sch_modifier_nonmonotonic;
3048 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003049 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003050 if (Schedule == OMP_sch_static_chunked)
3051 Schedule = OMP_sch_static_balanced_chunked;
3052 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003053 case OMPC_SCHEDULE_MODIFIER_last:
3054 case OMPC_SCHEDULE_MODIFIER_unknown:
3055 break;
3056 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003057 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003058}
3059
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003060void CGOpenMPRuntime::emitForDispatchInit(
3061 CodeGenFunction &CGF, SourceLocation Loc,
3062 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3063 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003064 if (!CGF.HaveInsertPoint())
3065 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003066 OpenMPSchedType Schedule = getRuntimeSchedule(
3067 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003068 assert(Ordered ||
3069 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003070 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3071 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003072 // Call __kmpc_dispatch_init(
3073 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3074 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3075 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003076
John McCall7f416cc2015-09-08 08:05:57 +00003077 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003078 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3079 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003080 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003081 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3082 CGF.Builder.getInt32(addMonoNonMonoModifier(
3083 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003084 DispatchValues.LB, // Lower
3085 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003086 CGF.Builder.getIntN(IVSize, 1), // Stride
3087 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003088 };
3089 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3090}
3091
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003092static void emitForStaticInitCall(
3093 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3094 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3095 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003096 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003097 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003098 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003099
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003100 assert(!Values.Ordered);
3101 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3102 Schedule == OMP_sch_static_balanced_chunked ||
3103 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3104 Schedule == OMP_dist_sch_static ||
3105 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003106
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003107 // Call __kmpc_for_static_init(
3108 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3109 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3110 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3111 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3112 llvm::Value *Chunk = Values.Chunk;
3113 if (Chunk == nullptr) {
3114 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3115 Schedule == OMP_dist_sch_static) &&
3116 "expected static non-chunked schedule");
3117 // If the Chunk was not specified in the clause - use default value 1.
3118 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3119 } else {
3120 assert((Schedule == OMP_sch_static_chunked ||
3121 Schedule == OMP_sch_static_balanced_chunked ||
3122 Schedule == OMP_ord_static_chunked ||
3123 Schedule == OMP_dist_sch_static_chunked) &&
3124 "expected static chunked schedule");
3125 }
3126 llvm::Value *Args[] = {
3127 UpdateLocation,
3128 ThreadId,
3129 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3130 M2)), // Schedule type
3131 Values.IL.getPointer(), // &isLastIter
3132 Values.LB.getPointer(), // &LB
3133 Values.UB.getPointer(), // &UB
3134 Values.ST.getPointer(), // &Stride
3135 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3136 Chunk // Chunk
3137 };
3138 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003139}
3140
John McCall7f416cc2015-09-08 08:05:57 +00003141void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3142 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003143 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003144 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003145 const StaticRTInput &Values) {
3146 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3147 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3148 assert(isOpenMPWorksharingDirective(DKind) &&
3149 "Expected loop-based or sections-based directive.");
3150 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3151 isOpenMPLoopDirective(DKind)
3152 ? OMP_IDENT_WORK_LOOP
3153 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003154 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003155 auto *StaticInitFunction =
3156 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003157 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003158 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003159}
John McCall7f416cc2015-09-08 08:05:57 +00003160
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003161void CGOpenMPRuntime::emitDistributeStaticInit(
3162 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003163 OpenMPDistScheduleClauseKind SchedKind,
3164 const CGOpenMPRuntime::StaticRTInput &Values) {
3165 OpenMPSchedType ScheduleNum =
3166 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3167 auto *UpdatedLocation =
3168 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003169 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003170 auto *StaticInitFunction =
3171 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003172 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3173 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003174 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003175}
3176
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003177void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003178 SourceLocation Loc,
3179 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003180 if (!CGF.HaveInsertPoint())
3181 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003182 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003183 llvm::Value *Args[] = {
3184 emitUpdateLocation(CGF, Loc,
3185 isOpenMPDistributeDirective(DKind)
3186 ? OMP_IDENT_WORK_DISTRIBUTE
3187 : isOpenMPLoopDirective(DKind)
3188 ? OMP_IDENT_WORK_LOOP
3189 : OMP_IDENT_WORK_SECTIONS),
3190 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003191 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3192 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003193}
3194
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003195void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3196 SourceLocation Loc,
3197 unsigned IVSize,
3198 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003199 if (!CGF.HaveInsertPoint())
3200 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003201 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003202 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003203 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3204}
3205
Alexander Musman92bdaab2015-03-12 13:37:50 +00003206llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3207 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003208 bool IVSigned, Address IL,
3209 Address LB, Address UB,
3210 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003211 // Call __kmpc_dispatch_next(
3212 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3213 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3214 // kmp_int[32|64] *p_stride);
3215 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003216 emitUpdateLocation(CGF, Loc),
3217 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003218 IL.getPointer(), // &isLastIter
3219 LB.getPointer(), // &Lower
3220 UB.getPointer(), // &Upper
3221 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003222 };
3223 llvm::Value *Call =
3224 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3225 return CGF.EmitScalarConversion(
3226 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003227 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003228}
3229
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003230void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3231 llvm::Value *NumThreads,
3232 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003233 if (!CGF.HaveInsertPoint())
3234 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003235 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3236 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003237 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003238 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003239 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3240 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003241}
3242
Alexey Bataev7f210c62015-06-18 13:40:03 +00003243void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3244 OpenMPProcBindClauseKind ProcBind,
3245 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003246 if (!CGF.HaveInsertPoint())
3247 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003248 // Constants for proc bind value accepted by the runtime.
3249 enum ProcBindTy {
3250 ProcBindFalse = 0,
3251 ProcBindTrue,
3252 ProcBindMaster,
3253 ProcBindClose,
3254 ProcBindSpread,
3255 ProcBindIntel,
3256 ProcBindDefault
3257 } RuntimeProcBind;
3258 switch (ProcBind) {
3259 case OMPC_PROC_BIND_master:
3260 RuntimeProcBind = ProcBindMaster;
3261 break;
3262 case OMPC_PROC_BIND_close:
3263 RuntimeProcBind = ProcBindClose;
3264 break;
3265 case OMPC_PROC_BIND_spread:
3266 RuntimeProcBind = ProcBindSpread;
3267 break;
3268 case OMPC_PROC_BIND_unknown:
3269 llvm_unreachable("Unsupported proc_bind value.");
3270 }
3271 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3272 llvm::Value *Args[] = {
3273 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3274 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3275 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3276}
3277
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003278void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3279 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003280 if (!CGF.HaveInsertPoint())
3281 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003282 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003283 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3284 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003285}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003286
Alexey Bataev62b63b12015-03-10 07:28:44 +00003287namespace {
3288/// \brief Indexes of fields for type kmp_task_t.
3289enum KmpTaskTFields {
3290 /// \brief List of shared variables.
3291 KmpTaskTShareds,
3292 /// \brief Task routine.
3293 KmpTaskTRoutine,
3294 /// \brief Partition id for the untied tasks.
3295 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003296 /// Function with call of destructors for private variables.
3297 Data1,
3298 /// Task priority.
3299 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003300 /// (Taskloops only) Lower bound.
3301 KmpTaskTLowerBound,
3302 /// (Taskloops only) Upper bound.
3303 KmpTaskTUpperBound,
3304 /// (Taskloops only) Stride.
3305 KmpTaskTStride,
3306 /// (Taskloops only) Is last iteration flag.
3307 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003308 /// (Taskloops only) Reduction data.
3309 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003310};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003311} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003312
Samuel Antaoee8fb302016-01-06 13:42:12 +00003313bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3314 // FIXME: Add other entries type when they become supported.
3315 return OffloadEntriesTargetRegion.empty();
3316}
3317
3318/// \brief Initialize target region entry.
3319void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3320 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3321 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003322 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003323 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3324 "only required for the device "
3325 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003326 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003327 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3328 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003329 ++OffloadingEntriesNum;
3330}
3331
3332void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3333 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3334 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003335 llvm::Constant *Addr, llvm::Constant *ID,
3336 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003337 // If we are emitting code for a target, the entry is already initialized,
3338 // only has to be registered.
3339 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003340 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003341 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003342 auto &Entry =
3343 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003344 assert(Entry.isValid() && "Entry not initialized!");
3345 Entry.setAddress(Addr);
3346 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003347 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003348 return;
3349 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003350 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003351 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003352 }
3353}
3354
3355bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003356 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3357 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003358 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3359 if (PerDevice == OffloadEntriesTargetRegion.end())
3360 return false;
3361 auto PerFile = PerDevice->second.find(FileID);
3362 if (PerFile == PerDevice->second.end())
3363 return false;
3364 auto PerParentName = PerFile->second.find(ParentName);
3365 if (PerParentName == PerFile->second.end())
3366 return false;
3367 auto PerLine = PerParentName->second.find(LineNum);
3368 if (PerLine == PerParentName->second.end())
3369 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003370 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003371 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003372 return false;
3373 return true;
3374}
3375
3376void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3377 const OffloadTargetRegionEntryInfoActTy &Action) {
3378 // Scan all target region entries and perform the provided action.
3379 for (auto &D : OffloadEntriesTargetRegion)
3380 for (auto &F : D.second)
3381 for (auto &P : F.second)
3382 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003383 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003384}
3385
3386/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3387/// \a Codegen. This is used to emit the two functions that register and
3388/// unregister the descriptor of the current compilation unit.
3389static llvm::Function *
3390createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3391 const RegionCodeGenTy &Codegen) {
3392 auto &C = CGM.getContext();
3393 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003394 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003395 Args.push_back(&DummyPtr);
3396
3397 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003398 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003399 auto FTy = CGM.getTypes().GetFunctionType(FI);
3400 auto *Fn =
3401 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3402 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3403 Codegen(CGF);
3404 CGF.FinishFunction();
3405 return Fn;
3406}
3407
3408llvm::Function *
3409CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3410
3411 // If we don't have entries or if we are emitting code for the device, we
3412 // don't need to do anything.
3413 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3414 return nullptr;
3415
3416 auto &M = CGM.getModule();
3417 auto &C = CGM.getContext();
3418
3419 // Get list of devices we care about
3420 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3421
3422 // We should be creating an offloading descriptor only if there are devices
3423 // specified.
3424 assert(!Devices.empty() && "No OpenMP offloading devices??");
3425
3426 // Create the external variables that will point to the begin and end of the
3427 // host entries section. These will be defined by the linker.
3428 auto *OffloadEntryTy =
3429 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3430 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3431 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003432 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003433 ".omp_offloading.entries_begin");
3434 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3435 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003436 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003437 ".omp_offloading.entries_end");
3438
3439 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003440 auto *DeviceImageTy = cast<llvm::StructType>(
3441 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003442 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003443 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003444
3445 for (unsigned i = 0; i < Devices.size(); ++i) {
3446 StringRef T = Devices[i].getTriple();
3447 auto *ImgBegin = new llvm::GlobalVariable(
3448 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003449 /*Initializer=*/nullptr,
3450 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451 auto *ImgEnd = new llvm::GlobalVariable(
3452 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003453 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003454
John McCall6c9f1fdb2016-11-19 08:17:24 +00003455 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3456 Dev.add(ImgBegin);
3457 Dev.add(ImgEnd);
3458 Dev.add(HostEntriesBegin);
3459 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003460 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003461 }
3462
3463 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003464 llvm::GlobalVariable *DeviceImages =
3465 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3466 CGM.getPointerAlign(),
3467 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003468 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003469
3470 // This is a Zero array to be used in the creation of the constant expressions
3471 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3472 llvm::Constant::getNullValue(CGM.Int32Ty)};
3473
3474 // Create the target region descriptor.
3475 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3476 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003477 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003478 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3479 DescInit.addInt(CGM.Int32Ty, Devices.size());
3480 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3481 DeviceImages,
3482 Index));
3483 DescInit.add(HostEntriesBegin);
3484 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003485
John McCall6c9f1fdb2016-11-19 08:17:24 +00003486 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3487 CGM.getPointerAlign(),
3488 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003489
3490 // Emit code to register or unregister the descriptor at execution
3491 // startup or closing, respectively.
3492
3493 // Create a variable to drive the registration and unregistration of the
3494 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3495 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3496 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003497 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003498
3499 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003500 CGM, ".omp_offloading.descriptor_unreg",
3501 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003502 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3503 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003504 });
3505 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003506 CGM, ".omp_offloading.descriptor_reg",
3507 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003508 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3509 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003510 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3511 });
George Rokos29d0f002017-05-27 03:03:13 +00003512 if (CGM.supportsCOMDAT()) {
3513 // It is sufficient to call registration function only once, so create a
3514 // COMDAT group for registration/unregistration functions and associated
3515 // data. That would reduce startup time and code size. Registration
3516 // function serves as a COMDAT group key.
3517 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3518 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3519 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3520 RegFn->setComdat(ComdatKey);
3521 UnRegFn->setComdat(ComdatKey);
3522 DeviceImages->setComdat(ComdatKey);
3523 Desc->setComdat(ComdatKey);
3524 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003525 return RegFn;
3526}
3527
Samuel Antao2de62b02016-02-13 23:35:10 +00003528void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003529 llvm::Constant *Addr, uint64_t Size,
3530 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003531 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003532 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3533 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3534 llvm::LLVMContext &C = CGM.getModule().getContext();
3535 llvm::Module &M = CGM.getModule();
3536
3537 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003538 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003539
3540 // Create constant string with the name.
3541 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3542
3543 llvm::GlobalVariable *Str =
3544 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3545 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3546 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003547 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003548 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3549
John McCall6c9f1fdb2016-11-19 08:17:24 +00003550 // We can't have any padding between symbols, so we need to have 1-byte
3551 // alignment.
3552 auto Align = CharUnits::fromQuantity(1);
3553
Samuel Antaoee8fb302016-01-06 13:42:12 +00003554 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003555 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003556 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3557 EntryInit.add(AddrPtr);
3558 EntryInit.add(StrPtr);
3559 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003560 EntryInit.addInt(CGM.Int32Ty, Flags);
3561 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003562 llvm::GlobalVariable *Entry =
3563 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3564 Align,
3565 /*constant*/ true,
3566 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003567
3568 // The entry has to be created in the section the linker expects it to be.
3569 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003570}
3571
3572void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3573 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003574 // can easily figure out what to emit. The produced metadata looks like
3575 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003576 //
3577 // !omp_offload.info = !{!1, ...}
3578 //
3579 // Right now we only generate metadata for function that contain target
3580 // regions.
3581
3582 // If we do not have entries, we dont need to do anything.
3583 if (OffloadEntriesInfoManager.empty())
3584 return;
3585
3586 llvm::Module &M = CGM.getModule();
3587 llvm::LLVMContext &C = M.getContext();
3588 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3589 OrderedEntries(OffloadEntriesInfoManager.size());
3590
3591 // Create the offloading info metadata node.
3592 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3593
Simon Pilgrim2c518802017-03-30 14:13:19 +00003594 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003595 auto getMDInt = [&](unsigned v) {
3596 return llvm::ConstantAsMetadata::get(
3597 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3598 };
3599
3600 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3601
3602 // Create function that emits metadata for each target region entry;
3603 auto &&TargetRegionMetadataEmitter = [&](
3604 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003605 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3606 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3607 // Generate metadata for target regions. Each entry of this metadata
3608 // contains:
3609 // - Entry 0 -> Kind of this type of metadata (0).
3610 // - Entry 1 -> Device ID of the file where the entry was identified.
3611 // - Entry 2 -> File ID of the file where the entry was identified.
3612 // - Entry 3 -> Mangled name of the function where the entry was identified.
3613 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003614 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003615 // The first element of the metadata node is the kind.
3616 Ops.push_back(getMDInt(E.getKind()));
3617 Ops.push_back(getMDInt(DeviceID));
3618 Ops.push_back(getMDInt(FileID));
3619 Ops.push_back(getMDString(ParentName));
3620 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003621 Ops.push_back(getMDInt(E.getOrder()));
3622
3623 // Save this entry in the right position of the ordered entries array.
3624 OrderedEntries[E.getOrder()] = &E;
3625
3626 // Add metadata to the named metadata node.
3627 MD->addOperand(llvm::MDNode::get(C, Ops));
3628 };
3629
3630 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3631 TargetRegionMetadataEmitter);
3632
3633 for (auto *E : OrderedEntries) {
3634 assert(E && "All ordered entries must exist!");
3635 if (auto *CE =
3636 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3637 E)) {
3638 assert(CE->getID() && CE->getAddress() &&
3639 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003640 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003641 } else
3642 llvm_unreachable("Unsupported entry kind.");
3643 }
3644}
3645
3646/// \brief Loads all the offload entries information from the host IR
3647/// metadata.
3648void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3649 // If we are in target mode, load the metadata from the host IR. This code has
3650 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3651
3652 if (!CGM.getLangOpts().OpenMPIsDevice)
3653 return;
3654
3655 if (CGM.getLangOpts().OMPHostIRFile.empty())
3656 return;
3657
3658 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3659 if (Buf.getError())
3660 return;
3661
3662 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003663 auto ME = expectedToErrorOrAndEmitErrors(
3664 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003665
3666 if (ME.getError())
3667 return;
3668
3669 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3670 if (!MD)
3671 return;
3672
3673 for (auto I : MD->operands()) {
3674 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3675
3676 auto getMDInt = [&](unsigned Idx) {
3677 llvm::ConstantAsMetadata *V =
3678 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3679 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3680 };
3681
3682 auto getMDString = [&](unsigned Idx) {
3683 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3684 return V->getString();
3685 };
3686
3687 switch (getMDInt(0)) {
3688 default:
3689 llvm_unreachable("Unexpected metadata!");
3690 break;
3691 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3692 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3693 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3694 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3695 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003696 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003697 break;
3698 }
3699 }
3700}
3701
Alexey Bataev62b63b12015-03-10 07:28:44 +00003702void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3703 if (!KmpRoutineEntryPtrTy) {
3704 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3705 auto &C = CGM.getContext();
3706 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3707 FunctionProtoType::ExtProtoInfo EPI;
3708 KmpRoutineEntryPtrQTy = C.getPointerType(
3709 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3710 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3711 }
3712}
3713
Alexey Bataevc71a4092015-09-11 10:29:41 +00003714static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3715 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003716 auto *Field = FieldDecl::Create(
3717 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3718 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3719 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3720 Field->setAccess(AS_public);
3721 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003722 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003723}
3724
Samuel Antaoee8fb302016-01-06 13:42:12 +00003725QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3726
3727 // Make sure the type of the entry is already created. This is the type we
3728 // have to create:
3729 // struct __tgt_offload_entry{
3730 // void *addr; // Pointer to the offload entry info.
3731 // // (function or global)
3732 // char *name; // Name of the function or global.
3733 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003734 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3735 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003736 // };
3737 if (TgtOffloadEntryQTy.isNull()) {
3738 ASTContext &C = CGM.getContext();
3739 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3740 RD->startDefinition();
3741 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3742 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3743 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003744 addFieldToRecordDecl(
3745 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3746 addFieldToRecordDecl(
3747 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003748 RD->completeDefinition();
3749 TgtOffloadEntryQTy = C.getRecordType(RD);
3750 }
3751 return TgtOffloadEntryQTy;
3752}
3753
3754QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3755 // These are the types we need to build:
3756 // struct __tgt_device_image{
3757 // void *ImageStart; // Pointer to the target code start.
3758 // void *ImageEnd; // Pointer to the target code end.
3759 // // We also add the host entries to the device image, as it may be useful
3760 // // for the target runtime to have access to that information.
3761 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3762 // // the entries.
3763 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3764 // // entries (non inclusive).
3765 // };
3766 if (TgtDeviceImageQTy.isNull()) {
3767 ASTContext &C = CGM.getContext();
3768 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3769 RD->startDefinition();
3770 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3771 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3772 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3773 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3774 RD->completeDefinition();
3775 TgtDeviceImageQTy = C.getRecordType(RD);
3776 }
3777 return TgtDeviceImageQTy;
3778}
3779
3780QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3781 // struct __tgt_bin_desc{
3782 // int32_t NumDevices; // Number of devices supported.
3783 // __tgt_device_image *DeviceImages; // Arrays of device images
3784 // // (one per device).
3785 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3786 // // entries.
3787 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3788 // // entries (non inclusive).
3789 // };
3790 if (TgtBinaryDescriptorQTy.isNull()) {
3791 ASTContext &C = CGM.getContext();
3792 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3793 RD->startDefinition();
3794 addFieldToRecordDecl(
3795 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3796 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3797 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3798 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3799 RD->completeDefinition();
3800 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3801 }
3802 return TgtBinaryDescriptorQTy;
3803}
3804
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003805namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003806struct PrivateHelpersTy {
3807 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3808 const VarDecl *PrivateElemInit)
3809 : Original(Original), PrivateCopy(PrivateCopy),
3810 PrivateElemInit(PrivateElemInit) {}
3811 const VarDecl *Original;
3812 const VarDecl *PrivateCopy;
3813 const VarDecl *PrivateElemInit;
3814};
3815typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003816} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003817
Alexey Bataev9e034042015-05-05 04:05:12 +00003818static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003819createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003820 if (!Privates.empty()) {
3821 auto &C = CGM.getContext();
3822 // Build struct .kmp_privates_t. {
3823 // /* private vars */
3824 // };
3825 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3826 RD->startDefinition();
3827 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003828 auto *VD = Pair.second.Original;
3829 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003830 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003831 auto *FD = addFieldToRecordDecl(C, RD, Type);
3832 if (VD->hasAttrs()) {
3833 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3834 E(VD->getAttrs().end());
3835 I != E; ++I)
3836 FD->addAttr(*I);
3837 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003838 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003839 RD->completeDefinition();
3840 return RD;
3841 }
3842 return nullptr;
3843}
3844
Alexey Bataev9e034042015-05-05 04:05:12 +00003845static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003846createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3847 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003848 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003849 auto &C = CGM.getContext();
3850 // Build struct kmp_task_t {
3851 // void * shareds;
3852 // kmp_routine_entry_t routine;
3853 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003854 // kmp_cmplrdata_t data1;
3855 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003856 // For taskloops additional fields:
3857 // kmp_uint64 lb;
3858 // kmp_uint64 ub;
3859 // kmp_int64 st;
3860 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003861 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003862 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003863 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3864 UD->startDefinition();
3865 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3866 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3867 UD->completeDefinition();
3868 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003869 auto *RD = C.buildImplicitRecord("kmp_task_t");
3870 RD->startDefinition();
3871 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3872 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3873 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003874 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3875 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003876 if (isOpenMPTaskLoopDirective(Kind)) {
3877 QualType KmpUInt64Ty =
3878 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3879 QualType KmpInt64Ty =
3880 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3881 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3882 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3883 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3884 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003885 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003886 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003887 RD->completeDefinition();
3888 return RD;
3889}
3890
3891static RecordDecl *
3892createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003893 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003894 auto &C = CGM.getContext();
3895 // Build struct kmp_task_t_with_privates {
3896 // kmp_task_t task_data;
3897 // .kmp_privates_t. privates;
3898 // };
3899 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3900 RD->startDefinition();
3901 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003902 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3903 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3904 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003905 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003906 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003907}
3908
3909/// \brief Emit a proxy function which accepts kmp_task_t as the second
3910/// argument.
3911/// \code
3912/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003913/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003914/// For taskloops:
3915/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003916/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003917/// return 0;
3918/// }
3919/// \endcode
3920static llvm::Value *
3921emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003922 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3923 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003924 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003925 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3926 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003927 auto &C = CGM.getContext();
3928 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003929 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3930 ImplicitParamDecl::Other);
3931 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3932 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3933 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003934 Args.push_back(&GtidArg);
3935 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003936 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003937 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003938 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3939 auto *TaskEntry =
3940 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3941 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003942 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003943 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003944 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3945
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003946 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003947 // tt,
3948 // For taskloops:
3949 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3950 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003951 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003952 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003953 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3954 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3955 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003956 auto *KmpTaskTWithPrivatesQTyRD =
3957 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003958 LValue Base =
3959 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003960 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3961 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3962 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003963 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003964
3965 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3966 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003967 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003968 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003969 CGF.ConvertTypeForMem(SharedsPtrTy));
3970
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003971 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3972 llvm::Value *PrivatesParam;
3973 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3974 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3975 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003976 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003977 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003978 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003979
Alexey Bataev7292c292016-04-25 12:22:29 +00003980 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3981 TaskPrivatesMap,
3982 CGF.Builder
3983 .CreatePointerBitCastOrAddrSpaceCast(
3984 TDBase.getAddress(), CGF.VoidPtrTy)
3985 .getPointer()};
3986 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3987 std::end(CommonArgs));
3988 if (isOpenMPTaskLoopDirective(Kind)) {
3989 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3990 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3991 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3992 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3993 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3994 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3995 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3996 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3997 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3998 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3999 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
4000 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004001 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4002 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
4003 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00004004 CallArgs.push_back(LBParam);
4005 CallArgs.push_back(UBParam);
4006 CallArgs.push_back(StParam);
4007 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004008 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004009 }
4010 CallArgs.push_back(SharedsParam);
4011
Alexey Bataev3c595a62017-08-14 15:01:03 +00004012 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4013 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004014 CGF.EmitStoreThroughLValue(
4015 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00004016 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004017 CGF.FinishFunction();
4018 return TaskEntry;
4019}
4020
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004021static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4022 SourceLocation Loc,
4023 QualType KmpInt32Ty,
4024 QualType KmpTaskTWithPrivatesPtrQTy,
4025 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00004026 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004027 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004028 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4029 ImplicitParamDecl::Other);
4030 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4031 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4032 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004033 Args.push_back(&GtidArg);
4034 Args.push_back(&TaskTypeArg);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004035 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004036 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004037 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
4038 auto *DestructorFn =
4039 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4040 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004041 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
4042 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004043 CodeGenFunction CGF(CGM);
4044 CGF.disableDebugInfo();
4045 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
4046 Args);
4047
Alexey Bataev31300ed2016-02-04 11:27:03 +00004048 LValue Base = CGF.EmitLoadOfPointerLValue(
4049 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4050 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004051 auto *KmpTaskTWithPrivatesQTyRD =
4052 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4053 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004054 Base = CGF.EmitLValueForField(Base, *FI);
4055 for (auto *Field :
4056 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4057 if (auto DtorKind = Field->getType().isDestructedType()) {
4058 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
4059 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4060 }
4061 }
4062 CGF.FinishFunction();
4063 return DestructorFn;
4064}
4065
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004066/// \brief Emit a privates mapping function for correct handling of private and
4067/// firstprivate variables.
4068/// \code
4069/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4070/// **noalias priv1,..., <tyn> **noalias privn) {
4071/// *priv1 = &.privates.priv1;
4072/// ...;
4073/// *privn = &.privates.privn;
4074/// }
4075/// \endcode
4076static llvm::Value *
4077emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004078 ArrayRef<const Expr *> PrivateVars,
4079 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004080 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004081 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004082 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004083 auto &C = CGM.getContext();
4084 FunctionArgList Args;
4085 ImplicitParamDecl TaskPrivatesArg(
4086 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004087 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4088 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004089 Args.push_back(&TaskPrivatesArg);
4090 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4091 unsigned Counter = 1;
4092 for (auto *E: PrivateVars) {
4093 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004094 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4095 C.getPointerType(C.getPointerType(E->getType()))
4096 .withConst()
4097 .withRestrict(),
4098 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004099 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4100 PrivateVarsPos[VD] = Counter;
4101 ++Counter;
4102 }
4103 for (auto *E : FirstprivateVars) {
4104 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004105 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4106 C.getPointerType(C.getPointerType(E->getType()))
4107 .withConst()
4108 .withRestrict(),
4109 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004110 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4111 PrivateVarsPos[VD] = Counter;
4112 ++Counter;
4113 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004114 for (auto *E: LastprivateVars) {
4115 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004116 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4117 C.getPointerType(C.getPointerType(E->getType()))
4118 .withConst()
4119 .withRestrict(),
4120 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004121 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4122 PrivateVarsPos[VD] = Counter;
4123 ++Counter;
4124 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004125 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004126 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004127 auto *TaskPrivatesMapTy =
4128 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4129 auto *TaskPrivatesMap = llvm::Function::Create(
4130 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4131 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004132 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4133 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004134 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004135 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004136 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004137 CodeGenFunction CGF(CGM);
4138 CGF.disableDebugInfo();
4139 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4140 TaskPrivatesMapFnInfo, Args);
4141
4142 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004143 LValue Base = CGF.EmitLoadOfPointerLValue(
4144 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4145 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004146 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4147 Counter = 0;
4148 for (auto *Field : PrivatesQTyRD->fields()) {
4149 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4150 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004151 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004152 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4153 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004154 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004155 ++Counter;
4156 }
4157 CGF.FinishFunction();
4158 return TaskPrivatesMap;
4159}
4160
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004161static bool stable_sort_comparator(const PrivateDataTy P1,
4162 const PrivateDataTy P2) {
4163 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004164}
4165
Alexey Bataevf93095a2016-05-05 08:46:22 +00004166/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004167static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004168 const OMPExecutableDirective &D,
4169 Address KmpTaskSharedsPtr, LValue TDBase,
4170 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4171 QualType SharedsTy, QualType SharedsPtrTy,
4172 const OMPTaskDataTy &Data,
4173 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4174 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004175 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4176 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4177 LValue SrcBase;
4178 if (!Data.FirstprivateVars.empty()) {
4179 SrcBase = CGF.MakeAddrLValue(
4180 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4181 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4182 SharedsTy);
4183 }
4184 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4185 cast<CapturedStmt>(*D.getAssociatedStmt()));
4186 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4187 for (auto &&Pair : Privates) {
4188 auto *VD = Pair.second.PrivateCopy;
4189 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004190 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4191 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004192 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004193 if (auto *Elem = Pair.second.PrivateElemInit) {
4194 auto *OriginalVD = Pair.second.Original;
4195 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4196 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4197 SharedRefLValue = CGF.MakeAddrLValue(
4198 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004199 SharedRefLValue.getType(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004200 LValueBaseInfo(AlignmentSource::Decl),
4201 SharedRefLValue.getTBAAInfo());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004202 QualType Type = OriginalVD->getType();
4203 if (Type->isArrayType()) {
4204 // Initialize firstprivate array.
4205 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4206 // Perform simple memcpy.
4207 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4208 SharedRefLValue.getAddress(), Type);
4209 } else {
4210 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004211 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004212 CGF.EmitOMPAggregateAssign(
4213 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4214 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4215 Address SrcElement) {
4216 // Clean up any temporaries needed by the initialization.
4217 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4218 InitScope.addPrivate(
4219 Elem, [SrcElement]() -> Address { return SrcElement; });
4220 (void)InitScope.Privatize();
4221 // Emit initialization for single element.
4222 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4223 CGF, &CapturesInfo);
4224 CGF.EmitAnyExprToMem(Init, DestElement,
4225 Init->getType().getQualifiers(),
4226 /*IsInitializer=*/false);
4227 });
4228 }
4229 } else {
4230 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4231 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4232 return SharedRefLValue.getAddress();
4233 });
4234 (void)InitScope.Privatize();
4235 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4236 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4237 /*capturedByInit=*/false);
4238 }
4239 } else
4240 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4241 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004242 ++FI;
4243 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004244}
4245
4246/// Check if duplication function is required for taskloops.
4247static bool checkInitIsRequired(CodeGenFunction &CGF,
4248 ArrayRef<PrivateDataTy> Privates) {
4249 bool InitRequired = false;
4250 for (auto &&Pair : Privates) {
4251 auto *VD = Pair.second.PrivateCopy;
4252 auto *Init = VD->getAnyInitializer();
4253 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4254 !CGF.isTrivialInitializer(Init));
4255 }
4256 return InitRequired;
4257}
4258
4259
4260/// Emit task_dup function (for initialization of
4261/// private/firstprivate/lastprivate vars and last_iter flag)
4262/// \code
4263/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4264/// lastpriv) {
4265/// // setup lastprivate flag
4266/// task_dst->last = lastpriv;
4267/// // could be constructor calls here...
4268/// }
4269/// \endcode
4270static llvm::Value *
4271emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4272 const OMPExecutableDirective &D,
4273 QualType KmpTaskTWithPrivatesPtrQTy,
4274 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4275 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4276 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4277 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4278 auto &C = CGM.getContext();
4279 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004280 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4281 KmpTaskTWithPrivatesPtrQTy,
4282 ImplicitParamDecl::Other);
4283 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4284 KmpTaskTWithPrivatesPtrQTy,
4285 ImplicitParamDecl::Other);
4286 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4287 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004288 Args.push_back(&DstArg);
4289 Args.push_back(&SrcArg);
4290 Args.push_back(&LastprivArg);
4291 auto &TaskDupFnInfo =
4292 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4293 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4294 auto *TaskDup =
4295 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4296 ".omp_task_dup.", &CGM.getModule());
4297 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4298 CodeGenFunction CGF(CGM);
4299 CGF.disableDebugInfo();
4300 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4301
4302 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4303 CGF.GetAddrOfLocalVar(&DstArg),
4304 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4305 // task_dst->liter = lastpriv;
4306 if (WithLastIter) {
4307 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4308 LValue Base = CGF.EmitLValueForField(
4309 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4310 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4311 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4312 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4313 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4314 }
4315
4316 // Emit initial values for private copies (if any).
4317 assert(!Privates.empty());
4318 Address KmpTaskSharedsPtr = Address::invalid();
4319 if (!Data.FirstprivateVars.empty()) {
4320 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4321 CGF.GetAddrOfLocalVar(&SrcArg),
4322 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4323 LValue Base = CGF.EmitLValueForField(
4324 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4325 KmpTaskSharedsPtr = Address(
4326 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4327 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4328 KmpTaskTShareds)),
4329 Loc),
4330 CGF.getNaturalTypeAlignment(SharedsTy));
4331 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004332 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4333 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004334 CGF.FinishFunction();
4335 return TaskDup;
4336}
4337
Alexey Bataev8a831592016-05-10 10:36:51 +00004338/// Checks if destructor function is required to be generated.
4339/// \return true if cleanups are required, false otherwise.
4340static bool
4341checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4342 bool NeedsCleanup = false;
4343 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4344 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4345 for (auto *FD : PrivateRD->fields()) {
4346 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4347 if (NeedsCleanup)
4348 break;
4349 }
4350 return NeedsCleanup;
4351}
4352
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004353CGOpenMPRuntime::TaskResultTy
4354CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4355 const OMPExecutableDirective &D,
4356 llvm::Value *TaskFunction, QualType SharedsTy,
4357 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004358 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004359 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004360 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004361 auto I = Data.PrivateCopies.begin();
4362 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004363 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4364 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004365 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004366 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4367 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004368 ++I;
4369 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004370 I = Data.FirstprivateCopies.begin();
4371 auto IElemInitRef = Data.FirstprivateInits.begin();
4372 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004373 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4374 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004375 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004376 PrivateHelpersTy(
4377 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4378 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004379 ++I;
4380 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004381 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004382 I = Data.LastprivateCopies.begin();
4383 for (auto *E : Data.LastprivateVars) {
4384 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4385 Privates.push_back(std::make_pair(
4386 C.getDeclAlign(VD),
4387 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4388 /*PrivateElemInit=*/nullptr)));
4389 ++I;
4390 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004391 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004392 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4393 // Build type kmp_routine_entry_t (if not built yet).
4394 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004395 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004396 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4397 if (SavedKmpTaskloopTQTy.isNull()) {
4398 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4399 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4400 }
4401 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004402 } else {
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004403 assert(D.getDirectiveKind() == OMPD_task &&
4404 "Expected taskloop or task directive");
4405 if (SavedKmpTaskTQTy.isNull()) {
4406 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4407 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4408 }
4409 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004410 }
4411 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004412 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004413 auto *KmpTaskTWithPrivatesQTyRD =
4414 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4415 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4416 QualType KmpTaskTWithPrivatesPtrQTy =
4417 C.getPointerType(KmpTaskTWithPrivatesQTy);
4418 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4419 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004420 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004421 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4422
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004423 // Emit initial values for private copies (if any).
4424 llvm::Value *TaskPrivatesMap = nullptr;
4425 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004426 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004427 if (!Privates.empty()) {
4428 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004429 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4430 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4431 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004432 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4433 TaskPrivatesMap, TaskPrivatesMapTy);
4434 } else {
4435 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4436 cast<llvm::PointerType>(TaskPrivatesMapTy));
4437 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004438 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4439 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004440 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004441 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4442 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4443 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004444
4445 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4446 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4447 // kmp_routine_entry_t *task_entry);
4448 // Task flags. Format is taken from
4449 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4450 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004451 enum {
4452 TiedFlag = 0x1,
4453 FinalFlag = 0x2,
4454 DestructorsFlag = 0x8,
4455 PriorityFlag = 0x20
4456 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004457 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004458 bool NeedsCleanup = false;
4459 if (!Privates.empty()) {
4460 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4461 if (NeedsCleanup)
4462 Flags = Flags | DestructorsFlag;
4463 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004464 if (Data.Priority.getInt())
4465 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004466 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004467 Data.Final.getPointer()
4468 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004469 CGF.Builder.getInt32(FinalFlag),
4470 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004471 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004472 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004473 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004474 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4475 getThreadID(CGF, Loc), TaskFlags,
4476 KmpTaskTWithPrivatesTySize, SharedsSize,
4477 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4478 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004479 auto *NewTask = CGF.EmitRuntimeCall(
4480 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004481 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4482 NewTask, KmpTaskTWithPrivatesPtrTy);
4483 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4484 KmpTaskTWithPrivatesQTy);
4485 LValue TDBase =
4486 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004487 // Fill the data in the resulting kmp_task_t record.
4488 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004489 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004490 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004491 KmpTaskSharedsPtr =
4492 Address(CGF.EmitLoadOfScalar(
4493 CGF.EmitLValueForField(
4494 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4495 KmpTaskTShareds)),
4496 Loc),
4497 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004498 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004499 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004500 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004501 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004502 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004503 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4504 SharedsTy, SharedsPtrTy, Data, Privates,
4505 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004506 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4507 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4508 Result.TaskDupFn = emitTaskDupFunction(
4509 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4510 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4511 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004512 }
4513 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004514 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4515 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004516 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004517 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4518 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4519 if (NeedsCleanup) {
4520 llvm::Value *DestructorFn = emitDestructorsFunction(
4521 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4522 KmpTaskTWithPrivatesQTy);
4523 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4524 LValue DestructorsLV = CGF.EmitLValueForField(
4525 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4526 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4527 DestructorFn, KmpRoutineEntryPtrTy),
4528 DestructorsLV);
4529 }
4530 // Set priority.
4531 if (Data.Priority.getInt()) {
4532 LValue Data2LV = CGF.EmitLValueForField(
4533 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4534 LValue PriorityLV = CGF.EmitLValueForField(
4535 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4536 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4537 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004538 Result.NewTask = NewTask;
4539 Result.TaskEntry = TaskEntry;
4540 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4541 Result.TDBase = TDBase;
4542 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4543 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004544}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004545
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004546void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4547 const OMPExecutableDirective &D,
4548 llvm::Value *TaskFunction,
4549 QualType SharedsTy, Address Shareds,
4550 const Expr *IfCond,
4551 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004552 if (!CGF.HaveInsertPoint())
4553 return;
4554
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004555 TaskResultTy Result =
4556 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4557 llvm::Value *NewTask = Result.NewTask;
4558 llvm::Value *TaskEntry = Result.TaskEntry;
4559 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4560 LValue TDBase = Result.TDBase;
4561 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004562 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004563 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004564 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004565 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004566 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004567 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004568 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004569 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4570 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004571 QualType FlagsTy =
4572 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004573 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4574 if (KmpDependInfoTy.isNull()) {
4575 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4576 KmpDependInfoRD->startDefinition();
4577 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4578 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4579 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4580 KmpDependInfoRD->completeDefinition();
4581 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004582 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004583 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004584 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004585 // Define type kmp_depend_info[<Dependences.size()>];
4586 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004587 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004588 ArrayType::Normal, /*IndexTypeQuals=*/0);
4589 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004590 DependenciesArray =
4591 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004592 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004593 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004594 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004595 llvm::Value *Size;
4596 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004597 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4598 LValue UpAddrLVal =
4599 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4600 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004601 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004602 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004603 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004604 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4605 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004606 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004607 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004608 auto Base = CGF.MakeAddrLValue(
4609 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004610 KmpDependInfoTy);
4611 // deps[i].base_addr = &<Dependences[i].second>;
4612 auto BaseAddrLVal = CGF.EmitLValueForField(
4613 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004614 CGF.EmitStoreOfScalar(
4615 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4616 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004617 // deps[i].len = sizeof(<Dependences[i].second>);
4618 auto LenLVal = CGF.EmitLValueForField(
4619 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4620 CGF.EmitStoreOfScalar(Size, LenLVal);
4621 // deps[i].flags = <Dependences[i].first>;
4622 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004623 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004624 case OMPC_DEPEND_in:
4625 DepKind = DepIn;
4626 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004627 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004628 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004629 case OMPC_DEPEND_inout:
4630 DepKind = DepInOut;
4631 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004632 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004633 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004634 case OMPC_DEPEND_unknown:
4635 llvm_unreachable("Unknown task dependence type");
4636 }
4637 auto FlagsLVal = CGF.EmitLValueForField(
4638 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4639 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4640 FlagsLVal);
4641 }
John McCall7f416cc2015-09-08 08:05:57 +00004642 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4643 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004644 CGF.VoidPtrTy);
4645 }
4646
Alexey Bataev62b63b12015-03-10 07:28:44 +00004647 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4648 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004649 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4650 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4651 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4652 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004653 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004654 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004655 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4656 llvm::Value *DepTaskArgs[7];
4657 if (NumDependencies) {
4658 DepTaskArgs[0] = UpLoc;
4659 DepTaskArgs[1] = ThreadID;
4660 DepTaskArgs[2] = NewTask;
4661 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4662 DepTaskArgs[4] = DependenciesArray.getPointer();
4663 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4664 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4665 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004666 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4667 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004668 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004669 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004670 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4671 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4672 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4673 }
John McCall7f416cc2015-09-08 08:05:57 +00004674 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004675 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004676 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004677 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004678 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004679 TaskArgs);
4680 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004681 // Check if parent region is untied and build return for untied task;
4682 if (auto *Region =
4683 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4684 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004685 };
John McCall7f416cc2015-09-08 08:05:57 +00004686
4687 llvm::Value *DepWaitTaskArgs[6];
4688 if (NumDependencies) {
4689 DepWaitTaskArgs[0] = UpLoc;
4690 DepWaitTaskArgs[1] = ThreadID;
4691 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4692 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4693 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4694 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4695 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004696 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004697 NumDependencies, &DepWaitTaskArgs,
4698 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004699 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004700 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4701 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4702 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4703 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4704 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004705 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004706 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004707 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004708 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004709 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4710 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004711 Action.Enter(CGF);
4712 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004713 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004714 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004715 };
4716
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004717 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4718 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004719 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4720 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004721 RegionCodeGenTy RCG(CodeGen);
4722 CommonActionTy Action(
4723 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4724 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4725 RCG.setAction(Action);
4726 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004727 };
John McCall7f416cc2015-09-08 08:05:57 +00004728
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004729 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004730 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004731 else {
4732 RegionCodeGenTy ThenRCG(ThenCodeGen);
4733 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004734 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004735}
4736
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004737void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4738 const OMPLoopDirective &D,
4739 llvm::Value *TaskFunction,
4740 QualType SharedsTy, Address Shareds,
4741 const Expr *IfCond,
4742 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004743 if (!CGF.HaveInsertPoint())
4744 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004745 TaskResultTy Result =
4746 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004747 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4748 // libcall.
4749 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4750 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4751 // sched, kmp_uint64 grainsize, void *task_dup);
4752 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4753 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4754 llvm::Value *IfVal;
4755 if (IfCond) {
4756 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4757 /*isSigned=*/true);
4758 } else
4759 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4760
4761 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004762 Result.TDBase,
4763 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004764 auto *LBVar =
4765 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4766 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4767 /*IsInitializer=*/true);
4768 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004769 Result.TDBase,
4770 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004771 auto *UBVar =
4772 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4773 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4774 /*IsInitializer=*/true);
4775 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004776 Result.TDBase,
4777 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004778 auto *StVar =
4779 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4780 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4781 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004782 // Store reductions address.
4783 LValue RedLVal = CGF.EmitLValueForField(
4784 Result.TDBase,
4785 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4786 if (Data.Reductions)
4787 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4788 else {
4789 CGF.EmitNullInitialization(RedLVal.getAddress(),
4790 CGF.getContext().VoidPtrTy);
4791 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004792 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004793 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004794 UpLoc,
4795 ThreadID,
4796 Result.NewTask,
4797 IfVal,
4798 LBLVal.getPointer(),
4799 UBLVal.getPointer(),
4800 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4801 llvm::ConstantInt::getNullValue(
4802 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004803 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004804 CGF.IntTy, Data.Schedule.getPointer()
4805 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004806 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004807 Data.Schedule.getPointer()
4808 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004809 /*isSigned=*/false)
4810 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004811 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4812 Result.TaskDupFn, CGF.VoidPtrTy)
4813 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004814 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4815}
4816
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004817/// \brief Emit reduction operation for each element of array (required for
4818/// array sections) LHS op = RHS.
4819/// \param Type Type of array.
4820/// \param LHSVar Variable on the left side of the reduction operation
4821/// (references element of array in original variable).
4822/// \param RHSVar Variable on the right side of the reduction operation
4823/// (references element of array in original variable).
4824/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4825/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004826static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004827 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4828 const VarDecl *RHSVar,
4829 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4830 const Expr *, const Expr *)> &RedOpGen,
4831 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4832 const Expr *UpExpr = nullptr) {
4833 // Perform element-by-element initialization.
4834 QualType ElementTy;
4835 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4836 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4837
4838 // Drill down to the base element type on both arrays.
4839 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4840 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4841
4842 auto RHSBegin = RHSAddr.getPointer();
4843 auto LHSBegin = LHSAddr.getPointer();
4844 // Cast from pointer to array type to pointer to single element.
4845 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4846 // The basic structure here is a while-do loop.
4847 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4848 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4849 auto IsEmpty =
4850 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4851 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4852
4853 // Enter the loop body, making that address the current address.
4854 auto EntryBB = CGF.Builder.GetInsertBlock();
4855 CGF.EmitBlock(BodyBB);
4856
4857 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4858
4859 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4860 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4861 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4862 Address RHSElementCurrent =
4863 Address(RHSElementPHI,
4864 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4865
4866 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4867 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4868 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4869 Address LHSElementCurrent =
4870 Address(LHSElementPHI,
4871 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4872
4873 // Emit copy.
4874 CodeGenFunction::OMPPrivateScope Scope(CGF);
4875 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4876 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4877 Scope.Privatize();
4878 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4879 Scope.ForceCleanup();
4880
4881 // Shift the address forward by one element.
4882 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4883 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4884 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4885 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4886 // Check whether we've reached the end.
4887 auto Done =
4888 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4889 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4890 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4891 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4892
4893 // Done.
4894 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4895}
4896
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004897/// Emit reduction combiner. If the combiner is a simple expression emit it as
4898/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4899/// UDR combiner function.
4900static void emitReductionCombiner(CodeGenFunction &CGF,
4901 const Expr *ReductionOp) {
4902 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4903 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4904 if (auto *DRE =
4905 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4906 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4907 std::pair<llvm::Function *, llvm::Function *> Reduction =
4908 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4909 RValue Func = RValue::get(Reduction.first);
4910 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4911 CGF.EmitIgnoredExpr(ReductionOp);
4912 return;
4913 }
4914 CGF.EmitIgnoredExpr(ReductionOp);
4915}
4916
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004917llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4918 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4919 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4920 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004921 auto &C = CGM.getContext();
4922
4923 // void reduction_func(void *LHSArg, void *RHSArg);
4924 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004925 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4926 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004927 Args.push_back(&LHSArg);
4928 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004929 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004930 auto *Fn = llvm::Function::Create(
4931 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4932 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004933 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004934 CodeGenFunction CGF(CGM);
4935 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4936
4937 // Dst = (void*[n])(LHSArg);
4938 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004939 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4940 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4941 ArgsType), CGF.getPointerAlign());
4942 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4943 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4944 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004945
4946 // ...
4947 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4948 // ...
4949 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004950 auto IPriv = Privates.begin();
4951 unsigned Idx = 0;
4952 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004953 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4954 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004955 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004956 });
4957 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4958 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004959 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004960 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004961 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004962 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004963 // Get array size and emit VLA type.
4964 ++Idx;
4965 Address Elem =
4966 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4967 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004968 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4969 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004970 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004971 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004972 CGF.EmitVariablyModifiedType(PrivTy);
4973 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004974 }
4975 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004976 IPriv = Privates.begin();
4977 auto ILHS = LHSExprs.begin();
4978 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004979 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004980 if ((*IPriv)->getType()->isArrayType()) {
4981 // Emit reduction for array section.
4982 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4983 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004984 EmitOMPAggregateReduction(
4985 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4986 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4987 emitReductionCombiner(CGF, E);
4988 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004989 } else
4990 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004991 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004992 ++IPriv;
4993 ++ILHS;
4994 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004995 }
4996 Scope.ForceCleanup();
4997 CGF.FinishFunction();
4998 return Fn;
4999}
5000
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005001void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5002 const Expr *ReductionOp,
5003 const Expr *PrivateRef,
5004 const DeclRefExpr *LHS,
5005 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005006 if (PrivateRef->getType()->isArrayType()) {
5007 // Emit reduction for array section.
5008 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5009 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5010 EmitOMPAggregateReduction(
5011 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5012 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5013 emitReductionCombiner(CGF, ReductionOp);
5014 });
5015 } else
5016 // Emit reduction for array subscript or single variable.
5017 emitReductionCombiner(CGF, ReductionOp);
5018}
5019
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005020void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005021 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005022 ArrayRef<const Expr *> LHSExprs,
5023 ArrayRef<const Expr *> RHSExprs,
5024 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005025 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005026 if (!CGF.HaveInsertPoint())
5027 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005028
5029 bool WithNowait = Options.WithNowait;
5030 bool SimpleReduction = Options.SimpleReduction;
5031
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005032 // Next code should be emitted for reduction:
5033 //
5034 // static kmp_critical_name lock = { 0 };
5035 //
5036 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5037 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5038 // ...
5039 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5040 // *(Type<n>-1*)rhs[<n>-1]);
5041 // }
5042 //
5043 // ...
5044 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5045 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5046 // RedList, reduce_func, &<lock>)) {
5047 // case 1:
5048 // ...
5049 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5050 // ...
5051 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5052 // break;
5053 // case 2:
5054 // ...
5055 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5056 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005057 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005058 // break;
5059 // default:;
5060 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005061 //
5062 // if SimpleReduction is true, only the next code is generated:
5063 // ...
5064 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5065 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005066
5067 auto &C = CGM.getContext();
5068
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005069 if (SimpleReduction) {
5070 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005071 auto IPriv = Privates.begin();
5072 auto ILHS = LHSExprs.begin();
5073 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005074 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005075 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5076 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005077 ++IPriv;
5078 ++ILHS;
5079 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005080 }
5081 return;
5082 }
5083
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005084 // 1. Build a list of reduction variables.
5085 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005086 auto Size = RHSExprs.size();
5087 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005088 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005089 // Reserve place for array size.
5090 ++Size;
5091 }
5092 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005093 QualType ReductionArrayTy =
5094 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5095 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005096 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005097 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005098 auto IPriv = Privates.begin();
5099 unsigned Idx = 0;
5100 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005101 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005102 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005103 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005104 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005105 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5106 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005107 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005108 // Store array size.
5109 ++Idx;
5110 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5111 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005112 llvm::Value *Size = CGF.Builder.CreateIntCast(
5113 CGF.getVLASize(
5114 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5115 .first,
5116 CGF.SizeTy, /*isSigned=*/false);
5117 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5118 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005119 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005120 }
5121
5122 // 2. Emit reduce_func().
5123 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005124 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5125 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005126
5127 // 3. Create static kmp_critical_name lock = { 0 };
5128 auto *Lock = getCriticalRegionLock(".reduction");
5129
5130 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5131 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005132 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005133 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005134 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005135 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5136 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005137 llvm::Value *Args[] = {
5138 IdentTLoc, // ident_t *<loc>
5139 ThreadId, // i32 <gtid>
5140 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5141 ReductionArrayTySize, // size_type sizeof(RedList)
5142 RL, // void *RedList
5143 ReductionFn, // void (*) (void *, void *) <reduce_func>
5144 Lock // kmp_critical_name *&<lock>
5145 };
5146 auto Res = CGF.EmitRuntimeCall(
5147 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5148 : OMPRTL__kmpc_reduce),
5149 Args);
5150
5151 // 5. Build switch(res)
5152 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5153 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5154
5155 // 6. Build case 1:
5156 // ...
5157 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5158 // ...
5159 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5160 // break;
5161 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5162 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5163 CGF.EmitBlock(Case1BB);
5164
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005165 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5166 llvm::Value *EndArgs[] = {
5167 IdentTLoc, // ident_t *<loc>
5168 ThreadId, // i32 <gtid>
5169 Lock // kmp_critical_name *&<lock>
5170 };
5171 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5172 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005173 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005174 auto IPriv = Privates.begin();
5175 auto ILHS = LHSExprs.begin();
5176 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005177 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005178 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5179 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005180 ++IPriv;
5181 ++ILHS;
5182 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005183 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005184 };
5185 RegionCodeGenTy RCG(CodeGen);
5186 CommonActionTy Action(
5187 nullptr, llvm::None,
5188 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5189 : OMPRTL__kmpc_end_reduce),
5190 EndArgs);
5191 RCG.setAction(Action);
5192 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005193
5194 CGF.EmitBranch(DefaultBB);
5195
5196 // 7. Build case 2:
5197 // ...
5198 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5199 // ...
5200 // break;
5201 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5202 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5203 CGF.EmitBlock(Case2BB);
5204
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005205 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5206 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005207 auto ILHS = LHSExprs.begin();
5208 auto IRHS = RHSExprs.begin();
5209 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005210 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005211 const Expr *XExpr = nullptr;
5212 const Expr *EExpr = nullptr;
5213 const Expr *UpExpr = nullptr;
5214 BinaryOperatorKind BO = BO_Comma;
5215 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5216 if (BO->getOpcode() == BO_Assign) {
5217 XExpr = BO->getLHS();
5218 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005219 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005220 }
5221 // Try to emit update expression as a simple atomic.
5222 auto *RHSExpr = UpExpr;
5223 if (RHSExpr) {
5224 // Analyze RHS part of the whole expression.
5225 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5226 RHSExpr->IgnoreParenImpCasts())) {
5227 // If this is a conditional operator, analyze its condition for
5228 // min/max reduction operator.
5229 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005230 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005231 if (auto *BORHS =
5232 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5233 EExpr = BORHS->getRHS();
5234 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005235 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005236 }
5237 if (XExpr) {
5238 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005239 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005240 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5241 const Expr *EExpr, const Expr *UpExpr) {
5242 LValue X = CGF.EmitLValue(XExpr);
5243 RValue E;
5244 if (EExpr)
5245 E = CGF.EmitAnyExpr(EExpr);
5246 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005247 X, E, BO, /*IsXLHSInRHSPart=*/true,
5248 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005249 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005250 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5251 PrivateScope.addPrivate(
5252 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5253 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5254 CGF.emitOMPSimpleStore(
5255 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5256 VD->getType().getNonReferenceType(), Loc);
5257 return LHSTemp;
5258 });
5259 (void)PrivateScope.Privatize();
5260 return CGF.EmitAnyExpr(UpExpr);
5261 });
5262 };
5263 if ((*IPriv)->getType()->isArrayType()) {
5264 // Emit atomic reduction for array section.
5265 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5266 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5267 AtomicRedGen, XExpr, EExpr, UpExpr);
5268 } else
5269 // Emit atomic reduction for array subscript or single variable.
5270 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5271 } else {
5272 // Emit as a critical region.
5273 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5274 const Expr *, const Expr *) {
5275 auto &RT = CGF.CGM.getOpenMPRuntime();
5276 RT.emitCriticalRegion(
5277 CGF, ".atomic_reduction",
5278 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5279 Action.Enter(CGF);
5280 emitReductionCombiner(CGF, E);
5281 },
5282 Loc);
5283 };
5284 if ((*IPriv)->getType()->isArrayType()) {
5285 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5286 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5287 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5288 CritRedGen);
5289 } else
5290 CritRedGen(CGF, nullptr, nullptr, nullptr);
5291 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005292 ++ILHS;
5293 ++IRHS;
5294 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005295 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005296 };
5297 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5298 if (!WithNowait) {
5299 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5300 llvm::Value *EndArgs[] = {
5301 IdentTLoc, // ident_t *<loc>
5302 ThreadId, // i32 <gtid>
5303 Lock // kmp_critical_name *&<lock>
5304 };
5305 CommonActionTy Action(nullptr, llvm::None,
5306 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5307 EndArgs);
5308 AtomicRCG.setAction(Action);
5309 AtomicRCG(CGF);
5310 } else
5311 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005312
5313 CGF.EmitBranch(DefaultBB);
5314 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5315}
5316
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005317/// Generates unique name for artificial threadprivate variables.
5318/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5319static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5320 unsigned N) {
5321 SmallString<256> Buffer;
5322 llvm::raw_svector_ostream Out(Buffer);
5323 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5324 return Out.str();
5325}
5326
5327/// Emits reduction initializer function:
5328/// \code
5329/// void @.red_init(void* %arg) {
5330/// %0 = bitcast void* %arg to <type>*
5331/// store <type> <init>, <type>* %0
5332/// ret void
5333/// }
5334/// \endcode
5335static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5336 SourceLocation Loc,
5337 ReductionCodeGen &RCG, unsigned N) {
5338 auto &C = CGM.getContext();
5339 FunctionArgList Args;
5340 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5341 Args.emplace_back(&Param);
5342 auto &FnInfo =
5343 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5344 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5345 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5346 ".red_init.", &CGM.getModule());
5347 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5348 CodeGenFunction CGF(CGM);
5349 CGF.disableDebugInfo();
5350 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5351 Address PrivateAddr = CGF.EmitLoadOfPointer(
5352 CGF.GetAddrOfLocalVar(&Param),
5353 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5354 llvm::Value *Size = nullptr;
5355 // If the size of the reduction item is non-constant, load it from global
5356 // threadprivate variable.
5357 if (RCG.getSizes(N).second) {
5358 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5359 CGF, CGM.getContext().getSizeType(),
5360 generateUniqueName("reduction_size", Loc, N));
5361 Size =
5362 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5363 CGM.getContext().getSizeType(), SourceLocation());
5364 }
5365 RCG.emitAggregateType(CGF, N, Size);
5366 LValue SharedLVal;
5367 // If initializer uses initializer from declare reduction construct, emit a
5368 // pointer to the address of the original reduction item (reuired by reduction
5369 // initializer)
5370 if (RCG.usesReductionInitializer(N)) {
5371 Address SharedAddr =
5372 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5373 CGF, CGM.getContext().VoidPtrTy,
5374 generateUniqueName("reduction", Loc, N));
5375 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5376 } else {
5377 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5378 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5379 CGM.getContext().VoidPtrTy);
5380 }
5381 // Emit the initializer:
5382 // %0 = bitcast void* %arg to <type>*
5383 // store <type> <init>, <type>* %0
5384 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5385 [](CodeGenFunction &) { return false; });
5386 CGF.FinishFunction();
5387 return Fn;
5388}
5389
5390/// Emits reduction combiner function:
5391/// \code
5392/// void @.red_comb(void* %arg0, void* %arg1) {
5393/// %lhs = bitcast void* %arg0 to <type>*
5394/// %rhs = bitcast void* %arg1 to <type>*
5395/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5396/// store <type> %2, <type>* %lhs
5397/// ret void
5398/// }
5399/// \endcode
5400static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5401 SourceLocation Loc,
5402 ReductionCodeGen &RCG, unsigned N,
5403 const Expr *ReductionOp,
5404 const Expr *LHS, const Expr *RHS,
5405 const Expr *PrivateRef) {
5406 auto &C = CGM.getContext();
5407 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5408 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5409 FunctionArgList Args;
5410 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5411 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5412 Args.emplace_back(&ParamInOut);
5413 Args.emplace_back(&ParamIn);
5414 auto &FnInfo =
5415 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5416 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5417 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5418 ".red_comb.", &CGM.getModule());
5419 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5420 CodeGenFunction CGF(CGM);
5421 CGF.disableDebugInfo();
5422 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5423 llvm::Value *Size = nullptr;
5424 // If the size of the reduction item is non-constant, load it from global
5425 // threadprivate variable.
5426 if (RCG.getSizes(N).second) {
5427 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5428 CGF, CGM.getContext().getSizeType(),
5429 generateUniqueName("reduction_size", Loc, N));
5430 Size =
5431 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5432 CGM.getContext().getSizeType(), SourceLocation());
5433 }
5434 RCG.emitAggregateType(CGF, N, Size);
5435 // Remap lhs and rhs variables to the addresses of the function arguments.
5436 // %lhs = bitcast void* %arg0 to <type>*
5437 // %rhs = bitcast void* %arg1 to <type>*
5438 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5439 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5440 // Pull out the pointer to the variable.
5441 Address PtrAddr = CGF.EmitLoadOfPointer(
5442 CGF.GetAddrOfLocalVar(&ParamInOut),
5443 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5444 return CGF.Builder.CreateElementBitCast(
5445 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5446 });
5447 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5448 // Pull out the pointer to the variable.
5449 Address PtrAddr = CGF.EmitLoadOfPointer(
5450 CGF.GetAddrOfLocalVar(&ParamIn),
5451 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5452 return CGF.Builder.CreateElementBitCast(
5453 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5454 });
5455 PrivateScope.Privatize();
5456 // Emit the combiner body:
5457 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5458 // store <type> %2, <type>* %lhs
5459 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5460 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5461 cast<DeclRefExpr>(RHS));
5462 CGF.FinishFunction();
5463 return Fn;
5464}
5465
5466/// Emits reduction finalizer function:
5467/// \code
5468/// void @.red_fini(void* %arg) {
5469/// %0 = bitcast void* %arg to <type>*
5470/// <destroy>(<type>* %0)
5471/// ret void
5472/// }
5473/// \endcode
5474static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5475 SourceLocation Loc,
5476 ReductionCodeGen &RCG, unsigned N) {
5477 if (!RCG.needCleanups(N))
5478 return nullptr;
5479 auto &C = CGM.getContext();
5480 FunctionArgList Args;
5481 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5482 Args.emplace_back(&Param);
5483 auto &FnInfo =
5484 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5485 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5486 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5487 ".red_fini.", &CGM.getModule());
5488 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5489 CodeGenFunction CGF(CGM);
5490 CGF.disableDebugInfo();
5491 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5492 Address PrivateAddr = CGF.EmitLoadOfPointer(
5493 CGF.GetAddrOfLocalVar(&Param),
5494 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5495 llvm::Value *Size = nullptr;
5496 // If the size of the reduction item is non-constant, load it from global
5497 // threadprivate variable.
5498 if (RCG.getSizes(N).second) {
5499 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5500 CGF, CGM.getContext().getSizeType(),
5501 generateUniqueName("reduction_size", Loc, N));
5502 Size =
5503 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5504 CGM.getContext().getSizeType(), SourceLocation());
5505 }
5506 RCG.emitAggregateType(CGF, N, Size);
5507 // Emit the finalizer body:
5508 // <destroy>(<type>* %0)
5509 RCG.emitCleanups(CGF, N, PrivateAddr);
5510 CGF.FinishFunction();
5511 return Fn;
5512}
5513
5514llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5515 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5516 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5517 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5518 return nullptr;
5519
5520 // Build typedef struct:
5521 // kmp_task_red_input {
5522 // void *reduce_shar; // shared reduction item
5523 // size_t reduce_size; // size of data item
5524 // void *reduce_init; // data initialization routine
5525 // void *reduce_fini; // data finalization routine
5526 // void *reduce_comb; // data combiner routine
5527 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5528 // } kmp_task_red_input_t;
5529 ASTContext &C = CGM.getContext();
5530 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5531 RD->startDefinition();
5532 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5533 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5534 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5535 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5536 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5537 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5538 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5539 RD->completeDefinition();
5540 QualType RDType = C.getRecordType(RD);
5541 unsigned Size = Data.ReductionVars.size();
5542 llvm::APInt ArraySize(/*numBits=*/64, Size);
5543 QualType ArrayRDType = C.getConstantArrayType(
5544 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5545 // kmp_task_red_input_t .rd_input.[Size];
5546 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5547 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5548 Data.ReductionOps);
5549 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5550 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5551 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5552 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5553 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5554 TaskRedInput.getPointer(), Idxs,
5555 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5556 ".rd_input.gep.");
5557 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5558 // ElemLVal.reduce_shar = &Shareds[Cnt];
5559 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5560 RCG.emitSharedLValue(CGF, Cnt);
5561 llvm::Value *CastedShared =
5562 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5563 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5564 RCG.emitAggregateType(CGF, Cnt);
5565 llvm::Value *SizeValInChars;
5566 llvm::Value *SizeVal;
5567 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5568 // We use delayed creation/initialization for VLAs, array sections and
5569 // custom reduction initializations. It is required because runtime does not
5570 // provide the way to pass the sizes of VLAs/array sections to
5571 // initializer/combiner/finalizer functions and does not pass the pointer to
5572 // original reduction item to the initializer. Instead threadprivate global
5573 // variables are used to store these values and use them in the functions.
5574 bool DelayedCreation = !!SizeVal;
5575 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5576 /*isSigned=*/false);
5577 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5578 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5579 // ElemLVal.reduce_init = init;
5580 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5581 llvm::Value *InitAddr =
5582 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5583 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5584 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5585 // ElemLVal.reduce_fini = fini;
5586 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5587 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5588 llvm::Value *FiniAddr = Fini
5589 ? CGF.EmitCastToVoidPtr(Fini)
5590 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5591 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5592 // ElemLVal.reduce_comb = comb;
5593 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5594 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5595 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5596 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5597 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5598 // ElemLVal.flags = 0;
5599 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5600 if (DelayedCreation) {
5601 CGF.EmitStoreOfScalar(
5602 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5603 FlagsLVal);
5604 } else
5605 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5606 }
5607 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5608 // *data);
5609 llvm::Value *Args[] = {
5610 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5611 /*isSigned=*/true),
5612 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5613 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5614 CGM.VoidPtrTy)};
5615 return CGF.EmitRuntimeCall(
5616 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5617}
5618
5619void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5620 SourceLocation Loc,
5621 ReductionCodeGen &RCG,
5622 unsigned N) {
5623 auto Sizes = RCG.getSizes(N);
5624 // Emit threadprivate global variable if the type is non-constant
5625 // (Sizes.second = nullptr).
5626 if (Sizes.second) {
5627 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5628 /*isSigned=*/false);
5629 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5630 CGF, CGM.getContext().getSizeType(),
5631 generateUniqueName("reduction_size", Loc, N));
5632 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5633 }
5634 // Store address of the original reduction item if custom initializer is used.
5635 if (RCG.usesReductionInitializer(N)) {
5636 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5637 CGF, CGM.getContext().VoidPtrTy,
5638 generateUniqueName("reduction", Loc, N));
5639 CGF.Builder.CreateStore(
5640 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5641 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5642 SharedAddr, /*IsVolatile=*/false);
5643 }
5644}
5645
5646Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5647 SourceLocation Loc,
5648 llvm::Value *ReductionsPtr,
5649 LValue SharedLVal) {
5650 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5651 // *d);
5652 llvm::Value *Args[] = {
5653 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5654 /*isSigned=*/true),
5655 ReductionsPtr,
5656 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5657 CGM.VoidPtrTy)};
5658 return Address(
5659 CGF.EmitRuntimeCall(
5660 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5661 SharedLVal.getAlignment());
5662}
5663
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005664void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5665 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005666 if (!CGF.HaveInsertPoint())
5667 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005668 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5669 // global_tid);
5670 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5671 // Ignore return result until untied tasks are supported.
5672 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005673 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5674 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005675}
5676
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005677void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005678 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005679 const RegionCodeGenTy &CodeGen,
5680 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005681 if (!CGF.HaveInsertPoint())
5682 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005683 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005684 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005685}
5686
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005687namespace {
5688enum RTCancelKind {
5689 CancelNoreq = 0,
5690 CancelParallel = 1,
5691 CancelLoop = 2,
5692 CancelSections = 3,
5693 CancelTaskgroup = 4
5694};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005695} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005696
5697static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5698 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005699 if (CancelRegion == OMPD_parallel)
5700 CancelKind = CancelParallel;
5701 else if (CancelRegion == OMPD_for)
5702 CancelKind = CancelLoop;
5703 else if (CancelRegion == OMPD_sections)
5704 CancelKind = CancelSections;
5705 else {
5706 assert(CancelRegion == OMPD_taskgroup);
5707 CancelKind = CancelTaskgroup;
5708 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005709 return CancelKind;
5710}
5711
5712void CGOpenMPRuntime::emitCancellationPointCall(
5713 CodeGenFunction &CGF, SourceLocation Loc,
5714 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005715 if (!CGF.HaveInsertPoint())
5716 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005717 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5718 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005719 if (auto *OMPRegionInfo =
5720 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005721 // For 'cancellation point taskgroup', the task region info may not have a
5722 // cancel. This may instead happen in another adjacent task.
5723 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005724 llvm::Value *Args[] = {
5725 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5726 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005727 // Ignore return result until untied tasks are supported.
5728 auto *Result = CGF.EmitRuntimeCall(
5729 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5730 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005731 // exit from construct;
5732 // }
5733 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5734 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5735 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5736 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5737 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005738 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005739 auto CancelDest =
5740 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005741 CGF.EmitBranchThroughCleanup(CancelDest);
5742 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5743 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005744 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005745}
5746
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005747void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005748 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005749 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005750 if (!CGF.HaveInsertPoint())
5751 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005752 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5753 // kmp_int32 cncl_kind);
5754 if (auto *OMPRegionInfo =
5755 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005756 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5757 PrePostActionTy &) {
5758 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005759 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005760 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005761 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5762 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005763 auto *Result = CGF.EmitRuntimeCall(
5764 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005765 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005766 // exit from construct;
5767 // }
5768 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5769 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5770 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5771 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5772 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005773 // exit from construct;
5774 auto CancelDest =
5775 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5776 CGF.EmitBranchThroughCleanup(CancelDest);
5777 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5778 };
5779 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005780 emitOMPIfClause(CGF, IfCond, ThenGen,
5781 [](CodeGenFunction &, PrePostActionTy &) {});
5782 else {
5783 RegionCodeGenTy ThenRCG(ThenGen);
5784 ThenRCG(CGF);
5785 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005786 }
5787}
Samuel Antaobed3c462015-10-02 16:14:20 +00005788
Samuel Antaoee8fb302016-01-06 13:42:12 +00005789/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005790/// consists of the file and device IDs as well as line number associated with
5791/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005792static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5793 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005794 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005795
5796 auto &SM = C.getSourceManager();
5797
5798 // The loc should be always valid and have a file ID (the user cannot use
5799 // #pragma directives in macros)
5800
5801 assert(Loc.isValid() && "Source location is expected to be always valid.");
5802 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5803
5804 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5805 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5806
5807 llvm::sys::fs::UniqueID ID;
5808 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5809 llvm_unreachable("Source file with target region no longer exists!");
5810
5811 DeviceID = ID.getDevice();
5812 FileID = ID.getFile();
5813 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005814}
5815
5816void CGOpenMPRuntime::emitTargetOutlinedFunction(
5817 const OMPExecutableDirective &D, StringRef ParentName,
5818 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005819 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005820 assert(!ParentName.empty() && "Invalid target region parent name!");
5821
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005822 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5823 IsOffloadEntry, CodeGen);
5824}
5825
5826void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5827 const OMPExecutableDirective &D, StringRef ParentName,
5828 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5829 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005830 // Create a unique name for the entry function using the source location
5831 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005832 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005833 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005834 //
5835 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005836 // mangled name of the function that encloses the target region and BB is the
5837 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005838
5839 unsigned DeviceID;
5840 unsigned FileID;
5841 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005842 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005843 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005844 SmallString<64> EntryFnName;
5845 {
5846 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005847 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5848 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005849 }
5850
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005851 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5852
Samuel Antaobed3c462015-10-02 16:14:20 +00005853 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005854 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005855 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005856
Samuel Antao6d004262016-06-16 18:39:34 +00005857 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005858
5859 // If this target outline function is not an offload entry, we don't need to
5860 // register it.
5861 if (!IsOffloadEntry)
5862 return;
5863
5864 // The target region ID is used by the runtime library to identify the current
5865 // target region, so it only has to be unique and not necessarily point to
5866 // anything. It could be the pointer to the outlined function that implements
5867 // the target region, but we aren't using that so that the compiler doesn't
5868 // need to keep that, and could therefore inline the host function if proven
5869 // worthwhile during optimization. In the other hand, if emitting code for the
5870 // device, the ID has to be the function address so that it can retrieved from
5871 // the offloading entry and launched by the runtime library. We also mark the
5872 // outlined function to have external linkage in case we are emitting code for
5873 // the device, because these functions will be entry points to the device.
5874
5875 if (CGM.getLangOpts().OpenMPIsDevice) {
5876 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5877 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5878 } else
5879 OutlinedFnID = new llvm::GlobalVariable(
5880 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5881 llvm::GlobalValue::PrivateLinkage,
5882 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5883
5884 // Register the information for the entry associated with this target region.
5885 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005886 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5887 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005888}
5889
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005890/// discard all CompoundStmts intervening between two constructs
5891static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5892 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5893 Body = CS->body_front();
5894
5895 return Body;
5896}
5897
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005898/// Emit the number of teams for a target directive. Inspect the num_teams
5899/// clause associated with a teams construct combined or closely nested
5900/// with the target directive.
5901///
5902/// Emit a team of size one for directives such as 'target parallel' that
5903/// have no associated teams construct.
5904///
5905/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005906static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005907emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5908 CodeGenFunction &CGF,
5909 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005910
5911 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5912 "teams directive expected to be "
5913 "emitted only for the host!");
5914
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005915 auto &Bld = CGF.Builder;
5916
5917 // If the target directive is combined with a teams directive:
5918 // Return the value in the num_teams clause, if any.
5919 // Otherwise, return 0 to denote the runtime default.
5920 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5921 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5922 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5923 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5924 /*IgnoreResultAssign*/ true);
5925 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5926 /*IsSigned=*/true);
5927 }
5928
5929 // The default value is 0.
5930 return Bld.getInt32(0);
5931 }
5932
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005933 // If the target directive is combined with a parallel directive but not a
5934 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005935 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5936 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005937
5938 // If the current target region has a teams region enclosed, we need to get
5939 // the number of teams to pass to the runtime function call. This is done
5940 // by generating the expression in a inlined region. This is required because
5941 // the expression is captured in the enclosing target environment when the
5942 // teams directive is not combined with target.
5943
5944 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5945
Alexey Bataev50a1c782017-12-01 21:31:08 +00005946 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005947 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00005948 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
5949 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5950 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5951 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5952 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
5953 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5954 /*IsSigned=*/true);
5955 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00005956
Alexey Bataev50a1c782017-12-01 21:31:08 +00005957 // If we have an enclosed teams directive but no num_teams clause we use
5958 // the default value 0.
5959 return Bld.getInt32(0);
5960 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00005961 }
5962
5963 // No teams associated with the directive.
5964 return nullptr;
5965}
5966
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005967/// Emit the number of threads for a target directive. Inspect the
5968/// thread_limit clause associated with a teams construct combined or closely
5969/// nested with the target directive.
5970///
5971/// Emit the num_threads clause for directives such as 'target parallel' that
5972/// have no associated teams construct.
5973///
5974/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005975static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005976emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5977 CodeGenFunction &CGF,
5978 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005979
5980 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5981 "teams directive expected to be "
5982 "emitted only for the host!");
5983
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005984 auto &Bld = CGF.Builder;
5985
5986 //
5987 // If the target directive is combined with a teams directive:
5988 // Return the value in the thread_limit clause, if any.
5989 //
5990 // If the target directive is combined with a parallel directive:
5991 // Return the value in the num_threads clause, if any.
5992 //
5993 // If both clauses are set, select the minimum of the two.
5994 //
5995 // If neither teams or parallel combined directives set the number of threads
5996 // in a team, return 0 to denote the runtime default.
5997 //
5998 // If this is not a teams directive return nullptr.
5999
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006000 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6001 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006002 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6003 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006004 llvm::Value *ThreadLimitVal = nullptr;
6005
6006 if (const auto *ThreadLimitClause =
6007 D.getSingleClause<OMPThreadLimitClause>()) {
6008 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6009 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6010 /*IgnoreResultAssign*/ true);
6011 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6012 /*IsSigned=*/true);
6013 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006014
6015 if (const auto *NumThreadsClause =
6016 D.getSingleClause<OMPNumThreadsClause>()) {
6017 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6018 llvm::Value *NumThreads =
6019 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6020 /*IgnoreResultAssign*/ true);
6021 NumThreadsVal =
6022 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6023 }
6024
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006025 // Select the lesser of thread_limit and num_threads.
6026 if (NumThreadsVal)
6027 ThreadLimitVal = ThreadLimitVal
6028 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6029 ThreadLimitVal),
6030 NumThreadsVal, ThreadLimitVal)
6031 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006032
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006033 // Set default value passed to the runtime if either teams or a target
6034 // parallel type directive is found but no clause is specified.
6035 if (!ThreadLimitVal)
6036 ThreadLimitVal = DefaultThreadLimitVal;
6037
6038 return ThreadLimitVal;
6039 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006040
Samuel Antaob68e2db2016-03-03 16:20:23 +00006041 // If the current target region has a teams region enclosed, we need to get
6042 // the thread limit to pass to the runtime function call. This is done
6043 // by generating the expression in a inlined region. This is required because
6044 // the expression is captured in the enclosing target environment when the
6045 // teams directive is not combined with target.
6046
6047 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6048
Alexey Bataev50a1c782017-12-01 21:31:08 +00006049 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006050 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006051 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6052 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
6053 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6054 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6055 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6056 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6057 /*IsSigned=*/true);
6058 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006059
Alexey Bataev50a1c782017-12-01 21:31:08 +00006060 // If we have an enclosed teams directive but no thread_limit clause we
6061 // use the default value 0.
6062 return CGF.Builder.getInt32(0);
6063 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006064 }
6065
6066 // No teams associated with the directive.
6067 return nullptr;
6068}
6069
Samuel Antao86ace552016-04-27 22:40:57 +00006070namespace {
6071// \brief Utility to handle information from clauses associated with a given
6072// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6073// It provides a convenient interface to obtain the information and generate
6074// code for that information.
6075class MappableExprsHandler {
6076public:
6077 /// \brief Values for bit flags used to specify the mapping type for
6078 /// offloading.
6079 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006080 /// \brief Allocate memory on the device and move data from host to device.
6081 OMP_MAP_TO = 0x01,
6082 /// \brief Allocate memory on the device and move data from device to host.
6083 OMP_MAP_FROM = 0x02,
6084 /// \brief Always perform the requested mapping action on the element, even
6085 /// if it was already mapped before.
6086 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006087 /// \brief Delete the element from the device environment, ignoring the
6088 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006089 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006090 /// \brief The element being mapped is a pointer-pointee pair; both the
6091 /// pointer and the pointee should be mapped.
6092 OMP_MAP_PTR_AND_OBJ = 0x10,
6093 /// \brief This flags signals that the base address of an entry should be
6094 /// passed to the target kernel as an argument.
6095 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006096 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006097 /// in the current position for the data being mapped. Used when we have the
6098 /// use_device_ptr clause.
6099 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006100 /// \brief This flag signals that the reference being passed is a pointer to
6101 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006102 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006103 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006104 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006105 /// Implicit map
6106 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006107 };
6108
Samuel Antaocc10b852016-07-28 14:23:26 +00006109 /// Class that associates information with a base pointer to be passed to the
6110 /// runtime library.
6111 class BasePointerInfo {
6112 /// The base pointer.
6113 llvm::Value *Ptr = nullptr;
6114 /// The base declaration that refers to this device pointer, or null if
6115 /// there is none.
6116 const ValueDecl *DevPtrDecl = nullptr;
6117
6118 public:
6119 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6120 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6121 llvm::Value *operator*() const { return Ptr; }
6122 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6123 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6124 };
6125
6126 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006127 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006128 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006129
6130private:
6131 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006132 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006133
6134 /// \brief Function the directive is being generated for.
6135 CodeGenFunction &CGF;
6136
Samuel Antaod486f842016-05-26 16:53:38 +00006137 /// \brief Set of all first private variables in the current directive.
6138 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006139 /// Set of all reduction variables in the current directive.
6140 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006141
Samuel Antao6890b092016-07-28 14:25:09 +00006142 /// Map between device pointer declarations and their expression components.
6143 /// The key value for declarations in 'this' is null.
6144 llvm::DenseMap<
6145 const ValueDecl *,
6146 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6147 DevPointersMap;
6148
Samuel Antao86ace552016-04-27 22:40:57 +00006149 llvm::Value *getExprTypeSize(const Expr *E) const {
6150 auto ExprTy = E->getType().getCanonicalType();
6151
6152 // Reference types are ignored for mapping purposes.
6153 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6154 ExprTy = RefTy->getPointeeType().getCanonicalType();
6155
6156 // Given that an array section is considered a built-in type, we need to
6157 // do the calculation based on the length of the section instead of relying
6158 // on CGF.getTypeSize(E->getType()).
6159 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6160 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6161 OAE->getBase()->IgnoreParenImpCasts())
6162 .getCanonicalType();
6163
6164 // If there is no length associated with the expression, that means we
6165 // are using the whole length of the base.
6166 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6167 return CGF.getTypeSize(BaseTy);
6168
6169 llvm::Value *ElemSize;
6170 if (auto *PTy = BaseTy->getAs<PointerType>())
6171 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6172 else {
6173 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6174 assert(ATy && "Expecting array type if not a pointer type.");
6175 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6176 }
6177
6178 // If we don't have a length at this point, that is because we have an
6179 // array section with a single element.
6180 if (!OAE->getLength())
6181 return ElemSize;
6182
6183 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6184 LengthVal =
6185 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6186 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6187 }
6188 return CGF.getTypeSize(ExprTy);
6189 }
6190
6191 /// \brief Return the corresponding bits for a given map clause modifier. Add
6192 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006193 /// map as the first one of a series of maps that relate to the same map
6194 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006195 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006196 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006197 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006198 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006199 switch (MapType) {
6200 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006201 case OMPC_MAP_release:
6202 // alloc and release is the default behavior in the runtime library, i.e.
6203 // if we don't pass any bits alloc/release that is what the runtime is
6204 // going to do. Therefore, we don't need to signal anything for these two
6205 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006206 break;
6207 case OMPC_MAP_to:
6208 Bits = OMP_MAP_TO;
6209 break;
6210 case OMPC_MAP_from:
6211 Bits = OMP_MAP_FROM;
6212 break;
6213 case OMPC_MAP_tofrom:
6214 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6215 break;
6216 case OMPC_MAP_delete:
6217 Bits = OMP_MAP_DELETE;
6218 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006219 default:
6220 llvm_unreachable("Unexpected map type!");
6221 break;
6222 }
6223 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006224 Bits |= OMP_MAP_PTR_AND_OBJ;
6225 if (AddIsTargetParamFlag)
6226 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006227 if (MapTypeModifier == OMPC_MAP_always)
6228 Bits |= OMP_MAP_ALWAYS;
6229 return Bits;
6230 }
6231
6232 /// \brief Return true if the provided expression is a final array section. A
6233 /// final array section, is one whose length can't be proved to be one.
6234 bool isFinalArraySectionExpression(const Expr *E) const {
6235 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6236
6237 // It is not an array section and therefore not a unity-size one.
6238 if (!OASE)
6239 return false;
6240
6241 // An array section with no colon always refer to a single element.
6242 if (OASE->getColonLoc().isInvalid())
6243 return false;
6244
6245 auto *Length = OASE->getLength();
6246
6247 // If we don't have a length we have to check if the array has size 1
6248 // for this dimension. Also, we should always expect a length if the
6249 // base type is pointer.
6250 if (!Length) {
6251 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6252 OASE->getBase()->IgnoreParenImpCasts())
6253 .getCanonicalType();
6254 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6255 return ATy->getSize().getSExtValue() != 1;
6256 // If we don't have a constant dimension length, we have to consider
6257 // the current section as having any size, so it is not necessarily
6258 // unitary. If it happen to be unity size, that's user fault.
6259 return true;
6260 }
6261
6262 // Check if the length evaluates to 1.
6263 llvm::APSInt ConstLength;
6264 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6265 return true; // Can have more that size 1.
6266
6267 return ConstLength.getSExtValue() != 1;
6268 }
6269
6270 /// \brief Generate the base pointers, section pointers, sizes and map type
6271 /// bits for the provided map type, map modifier, and expression components.
6272 /// \a IsFirstComponent should be set to true if the provided set of
6273 /// components is the first associated with a capture.
6274 void generateInfoForComponentList(
6275 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6276 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006277 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006278 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006279 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006280
6281 // The following summarizes what has to be generated for each map and the
6282 // types bellow. The generated information is expressed in this order:
6283 // base pointer, section pointer, size, flags
6284 // (to add to the ones that come from the map type and modifier).
6285 //
6286 // double d;
6287 // int i[100];
6288 // float *p;
6289 //
6290 // struct S1 {
6291 // int i;
6292 // float f[50];
6293 // }
6294 // struct S2 {
6295 // int i;
6296 // float f[50];
6297 // S1 s;
6298 // double *p;
6299 // struct S2 *ps;
6300 // }
6301 // S2 s;
6302 // S2 *ps;
6303 //
6304 // map(d)
6305 // &d, &d, sizeof(double), noflags
6306 //
6307 // map(i)
6308 // &i, &i, 100*sizeof(int), noflags
6309 //
6310 // map(i[1:23])
6311 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6312 //
6313 // map(p)
6314 // &p, &p, sizeof(float*), noflags
6315 //
6316 // map(p[1:24])
6317 // p, &p[1], 24*sizeof(float), noflags
6318 //
6319 // map(s)
6320 // &s, &s, sizeof(S2), noflags
6321 //
6322 // map(s.i)
6323 // &s, &(s.i), sizeof(int), noflags
6324 //
6325 // map(s.s.f)
6326 // &s, &(s.i.f), 50*sizeof(int), noflags
6327 //
6328 // map(s.p)
6329 // &s, &(s.p), sizeof(double*), noflags
6330 //
6331 // map(s.p[:22], s.a s.b)
6332 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006333 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006334 //
6335 // map(s.ps)
6336 // &s, &(s.ps), sizeof(S2*), noflags
6337 //
6338 // map(s.ps->s.i)
6339 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006340 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006341 //
6342 // map(s.ps->ps)
6343 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006344 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006345 //
6346 // map(s.ps->ps->ps)
6347 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006348 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6349 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006350 //
6351 // map(s.ps->ps->s.f[:22])
6352 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006353 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6354 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006355 //
6356 // map(ps)
6357 // &ps, &ps, sizeof(S2*), noflags
6358 //
6359 // map(ps->i)
6360 // ps, &(ps->i), sizeof(int), noflags
6361 //
6362 // map(ps->s.f)
6363 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6364 //
6365 // map(ps->p)
6366 // ps, &(ps->p), sizeof(double*), noflags
6367 //
6368 // map(ps->p[:22])
6369 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006370 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006371 //
6372 // map(ps->ps)
6373 // ps, &(ps->ps), sizeof(S2*), noflags
6374 //
6375 // map(ps->ps->s.i)
6376 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006377 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006378 //
6379 // map(ps->ps->ps)
6380 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006381 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006382 //
6383 // map(ps->ps->ps->ps)
6384 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006385 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6386 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006387 //
6388 // map(ps->ps->ps->s.f[:22])
6389 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006390 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6391 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006392
6393 // Track if the map information being generated is the first for a capture.
6394 bool IsCaptureFirstInfo = IsFirstComponentList;
6395
6396 // Scan the components from the base to the complete expression.
6397 auto CI = Components.rbegin();
6398 auto CE = Components.rend();
6399 auto I = CI;
6400
6401 // Track if the map information being generated is the first for a list of
6402 // components.
6403 bool IsExpressionFirstInfo = true;
6404 llvm::Value *BP = nullptr;
6405
6406 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6407 // The base is the 'this' pointer. The content of the pointer is going
6408 // to be the base of the field being mapped.
6409 BP = CGF.EmitScalarExpr(ME->getBase());
6410 } else {
6411 // The base is the reference to the variable.
6412 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006413 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006414
6415 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006416 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006417 // reference. References are ignored for mapping purposes.
6418 QualType Ty =
6419 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6420 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6421 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006422 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006423 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006424 .getPointer();
6425
6426 // We do not need to generate individual map information for the
6427 // pointer, it can be associated with the combined storage.
6428 ++I;
6429 }
6430 }
6431
George Rokos63bc9d62017-11-21 18:25:12 +00006432 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006433 for (; I != CE; ++I) {
6434 auto Next = std::next(I);
6435
6436 // We need to generate the addresses and sizes if this is the last
6437 // component, if the component is a pointer or if it is an array section
6438 // whose length can't be proved to be one. If this is a pointer, it
6439 // becomes the base address for the following components.
6440
6441 // A final array section, is one whose length can't be proved to be one.
6442 bool IsFinalArraySection =
6443 isFinalArraySectionExpression(I->getAssociatedExpression());
6444
6445 // Get information on whether the element is a pointer. Have to do a
6446 // special treatment for array sections given that they are built-in
6447 // types.
6448 const auto *OASE =
6449 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6450 bool IsPointer =
6451 (OASE &&
6452 OMPArraySectionExpr::getBaseOriginalType(OASE)
6453 .getCanonicalType()
6454 ->isAnyPointerType()) ||
6455 I->getAssociatedExpression()->getType()->isAnyPointerType();
6456
6457 if (Next == CE || IsPointer || IsFinalArraySection) {
6458
6459 // If this is not the last component, we expect the pointer to be
6460 // associated with an array expression or member expression.
6461 assert((Next == CE ||
6462 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6463 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6464 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6465 "Unexpected expression");
6466
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006467 llvm::Value *LB =
6468 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006469 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6470
Samuel Antao03a3cec2016-07-27 22:52:16 +00006471 // If we have a member expression and the current component is a
6472 // reference, we have to map the reference too. Whenever we have a
6473 // reference, the section that reference refers to is going to be a
6474 // load instruction from the storage assigned to the reference.
6475 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6476 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6477 auto *LI = cast<llvm::LoadInst>(LB);
6478 auto *RefAddr = LI->getPointerOperand();
6479
6480 BasePointers.push_back(BP);
6481 Pointers.push_back(RefAddr);
6482 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006483 Types.push_back(DefaultFlags |
6484 getMapTypeBits(
6485 /*MapType*/ OMPC_MAP_alloc,
6486 /*MapTypeModifier=*/OMPC_MAP_unknown,
6487 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006488 IsExpressionFirstInfo = false;
6489 IsCaptureFirstInfo = false;
6490 // The reference will be the next base address.
6491 BP = RefAddr;
6492 }
6493
6494 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006495 Pointers.push_back(LB);
6496 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006497
Samuel Antao6782e942016-05-26 16:48:10 +00006498 // We need to add a pointer flag for each map that comes from the
6499 // same expression except for the first one. We also need to signal
6500 // this map is the first one that relates with the current capture
6501 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006502 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6503 !IsExpressionFirstInfo,
6504 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006505
6506 // If we have a final array section, we are done with this expression.
6507 if (IsFinalArraySection)
6508 break;
6509
6510 // The pointer becomes the base for the next element.
6511 if (Next != CE)
6512 BP = LB;
6513
6514 IsExpressionFirstInfo = false;
6515 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006516 }
6517 }
6518 }
6519
Samuel Antaod486f842016-05-26 16:53:38 +00006520 /// \brief Return the adjusted map modifiers if the declaration a capture
6521 /// refers to appears in a first-private clause. This is expected to be used
6522 /// only with directives that start with 'target'.
6523 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6524 unsigned CurrentModifiers) {
6525 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6526
6527 // A first private variable captured by reference will use only the
6528 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6529 // declaration is known as first-private in this handler.
6530 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
George Rokos065755d2017-11-07 18:27:04 +00006531 return MappableExprsHandler::OMP_MAP_PRIVATE |
Samuel Antaod486f842016-05-26 16:53:38 +00006532 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006533 // Reduction variable will use only the 'private ptr' and 'map to_from'
6534 // flag.
6535 if (ReductionDecls.count(Cap.getCapturedVar())) {
6536 return MappableExprsHandler::OMP_MAP_TO |
6537 MappableExprsHandler::OMP_MAP_FROM;
6538 }
Samuel Antaod486f842016-05-26 16:53:38 +00006539
6540 // We didn't modify anything.
6541 return CurrentModifiers;
6542 }
6543
Samuel Antao86ace552016-04-27 22:40:57 +00006544public:
6545 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006546 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006547 // Extract firstprivate clause information.
6548 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6549 for (const auto *D : C->varlists())
6550 FirstPrivateDecls.insert(
6551 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006552 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
6553 for (const auto *D : C->varlists()) {
6554 ReductionDecls.insert(
6555 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6556 }
6557 }
Samuel Antao6890b092016-07-28 14:25:09 +00006558 // Extract device pointer clause information.
6559 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6560 for (auto L : C->component_lists())
6561 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006562 }
Samuel Antao86ace552016-04-27 22:40:57 +00006563
6564 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006565 /// types for the extracted mappable expressions. Also, for each item that
6566 /// relates with a device pointer, a pair of the relevant declaration and
6567 /// index where it occurs is appended to the device pointers info array.
6568 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006569 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6570 MapFlagsArrayTy &Types) const {
6571 BasePointers.clear();
6572 Pointers.clear();
6573 Sizes.clear();
6574 Types.clear();
6575
6576 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006577 /// Kind that defines how a device pointer has to be returned.
6578 enum ReturnPointerKind {
6579 // Don't have to return any pointer.
6580 RPK_None,
6581 // Pointer is the base of the declaration.
6582 RPK_Base,
6583 // Pointer is a member of the base declaration - 'this'
6584 RPK_Member,
6585 // Pointer is a reference and a member of the base declaration - 'this'
6586 RPK_MemberReference,
6587 };
Samuel Antao86ace552016-04-27 22:40:57 +00006588 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006589 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6590 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6591 ReturnPointerKind ReturnDevicePointer = RPK_None;
6592 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006593
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006594 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006595 MapInfo(
6596 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6597 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006598 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006599 : Components(Components), MapType(MapType),
6600 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006601 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006602 };
6603
6604 // We have to process the component lists that relate with the same
6605 // declaration in a single chunk so that we can generate the map flags
6606 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006607 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006608
6609 // Helper function to fill the information map for the different supported
6610 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006611 auto &&InfoGen = [&Info](
6612 const ValueDecl *D,
6613 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6614 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006615 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006616 const ValueDecl *VD =
6617 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006618 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6619 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006620 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006621
Paul Robinson78fb1322016-08-01 22:12:46 +00006622 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006623 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006624 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006625 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006626 MapInfo::RPK_None, C->isImplicit());
6627 }
Paul Robinson15c84002016-07-29 20:46:16 +00006628 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006629 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006630 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006631 MapInfo::RPK_None, C->isImplicit());
6632 }
Paul Robinson15c84002016-07-29 20:46:16 +00006633 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006634 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006635 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006636 MapInfo::RPK_None, C->isImplicit());
6637 }
Samuel Antao86ace552016-04-27 22:40:57 +00006638
Samuel Antaocc10b852016-07-28 14:23:26 +00006639 // Look at the use_device_ptr clause information and mark the existing map
6640 // entries as such. If there is no map information for an entry in the
6641 // use_device_ptr list, we create one with map type 'alloc' and zero size
6642 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006643 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006644 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006645 for (auto L : C->component_lists()) {
6646 assert(!L.second.empty() && "Not expecting empty list of components!");
6647 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6648 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6649 auto *IE = L.second.back().getAssociatedExpression();
6650 // If the first component is a member expression, we have to look into
6651 // 'this', which maps to null in the map of map information. Otherwise
6652 // look directly for the information.
6653 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6654
6655 // We potentially have map information for this declaration already.
6656 // Look for the first set of components that refer to it.
6657 if (It != Info.end()) {
6658 auto CI = std::find_if(
6659 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6660 return MI.Components.back().getAssociatedDeclaration() == VD;
6661 });
6662 // If we found a map entry, signal that the pointer has to be returned
6663 // and move on to the next declaration.
6664 if (CI != It->second.end()) {
6665 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6666 ? (VD->getType()->isReferenceType()
6667 ? MapInfo::RPK_MemberReference
6668 : MapInfo::RPK_Member)
6669 : MapInfo::RPK_Base;
6670 continue;
6671 }
6672 }
6673
6674 // We didn't find any match in our map information - generate a zero
6675 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006676 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006677 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006678 this->CGF
6679 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006680 .getScalarVal();
6681 BasePointers.push_back({Ptr, VD});
6682 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006683 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00006684 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00006685 }
6686
Samuel Antao86ace552016-04-27 22:40:57 +00006687 for (auto &M : Info) {
6688 // We need to know when we generate information for the first component
6689 // associated with a capture, because the mapping flags depend on it.
6690 bool IsFirstComponentList = true;
6691 for (MapInfo &L : M.second) {
6692 assert(!L.Components.empty() &&
6693 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006694
6695 // Remember the current base pointer index.
6696 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006697 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006698 this->generateInfoForComponentList(
6699 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6700 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006701
6702 // If this entry relates with a device pointer, set the relevant
6703 // declaration and add the 'return pointer' flag.
6704 if (IsFirstComponentList &&
6705 L.ReturnDevicePointer != MapInfo::RPK_None) {
6706 // If the pointer is not the base of the map, we need to skip the
6707 // base. If it is a reference in a member field, we also need to skip
6708 // the map of the reference.
6709 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6710 ++CurrentBasePointersIdx;
6711 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6712 ++CurrentBasePointersIdx;
6713 }
6714 assert(BasePointers.size() > CurrentBasePointersIdx &&
6715 "Unexpected number of mapped base pointers.");
6716
6717 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6718 assert(RelevantVD &&
6719 "No relevant declaration related with device pointer??");
6720
6721 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00006722 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006723 }
Samuel Antao86ace552016-04-27 22:40:57 +00006724 IsFirstComponentList = false;
6725 }
6726 }
6727 }
6728
6729 /// \brief Generate the base pointers, section pointers, sizes and map types
6730 /// associated to a given capture.
6731 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006732 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006733 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006734 MapValuesArrayTy &Pointers,
6735 MapValuesArrayTy &Sizes,
6736 MapFlagsArrayTy &Types) const {
6737 assert(!Cap->capturesVariableArrayType() &&
6738 "Not expecting to generate map info for a variable array type!");
6739
6740 BasePointers.clear();
6741 Pointers.clear();
6742 Sizes.clear();
6743 Types.clear();
6744
Samuel Antao6890b092016-07-28 14:25:09 +00006745 // We need to know when we generating information for the first component
6746 // associated with a capture, because the mapping flags depend on it.
6747 bool IsFirstComponentList = true;
6748
Samuel Antao86ace552016-04-27 22:40:57 +00006749 const ValueDecl *VD =
6750 Cap->capturesThis()
6751 ? nullptr
6752 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6753
Samuel Antao6890b092016-07-28 14:25:09 +00006754 // If this declaration appears in a is_device_ptr clause we just have to
6755 // pass the pointer by value. If it is a reference to a declaration, we just
6756 // pass its value, otherwise, if it is a member expression, we need to map
6757 // 'to' the field.
6758 if (!VD) {
6759 auto It = DevPointersMap.find(VD);
6760 if (It != DevPointersMap.end()) {
6761 for (auto L : It->second) {
6762 generateInfoForComponentList(
6763 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006764 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6765 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006766 IsFirstComponentList = false;
6767 }
6768 return;
6769 }
6770 } else if (DevPointersMap.count(VD)) {
6771 BasePointers.push_back({Arg, VD});
6772 Pointers.push_back(Arg);
6773 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00006774 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00006775 return;
6776 }
6777
Paul Robinson78fb1322016-08-01 22:12:46 +00006778 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006779 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006780 for (auto L : C->decl_component_lists(VD)) {
6781 assert(L.first == VD &&
6782 "We got information for the wrong declaration??");
6783 assert(!L.second.empty() &&
6784 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006785 generateInfoForComponentList(
6786 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6787 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006788 IsFirstComponentList = false;
6789 }
6790
6791 return;
6792 }
Samuel Antaod486f842016-05-26 16:53:38 +00006793
6794 /// \brief Generate the default map information for a given capture \a CI,
6795 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006796 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6797 const FieldDecl &RI, llvm::Value *CV,
6798 MapBaseValuesArrayTy &CurBasePointers,
6799 MapValuesArrayTy &CurPointers,
6800 MapValuesArrayTy &CurSizes,
6801 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006802
6803 // Do the default mapping.
6804 if (CI.capturesThis()) {
6805 CurBasePointers.push_back(CV);
6806 CurPointers.push_back(CV);
6807 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6808 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6809 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006810 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006811 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006812 CurBasePointers.push_back(CV);
6813 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006814 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006815 // We have to signal to the runtime captures passed by value that are
6816 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00006817 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006818 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6819 } else {
6820 // Pointers are implicitly mapped with a zero size and no flags
6821 // (other than first map that is added for all implicit maps).
6822 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006823 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6824 }
6825 } else {
6826 assert(CI.capturesVariable() && "Expected captured reference.");
6827 CurBasePointers.push_back(CV);
6828 CurPointers.push_back(CV);
6829
6830 const ReferenceType *PtrTy =
6831 cast<ReferenceType>(RI.getType().getTypePtr());
6832 QualType ElementType = PtrTy->getPointeeType();
6833 CurSizes.push_back(CGF.getTypeSize(ElementType));
6834 // The default map type for a scalar/complex type is 'to' because by
6835 // default the value doesn't have to be retrieved. For an aggregate
6836 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006837 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
6838 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
6839 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00006840 }
George Rokos065755d2017-11-07 18:27:04 +00006841 // Every default map produces a single argument which is a target parameter.
6842 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00006843 }
Samuel Antao86ace552016-04-27 22:40:57 +00006844};
Samuel Antaodf158d52016-04-27 22:58:19 +00006845
6846enum OpenMPOffloadingReservedDeviceIDs {
6847 /// \brief Device ID if the device was not defined, runtime should get it
6848 /// from environment variables in the spec.
6849 OMP_DEVICEID_UNDEF = -1,
6850};
6851} // anonymous namespace
6852
6853/// \brief Emit the arrays used to pass the captures and map information to the
6854/// offloading runtime library. If there is no map or capture information,
6855/// return nullptr by reference.
6856static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006857emitOffloadingArrays(CodeGenFunction &CGF,
6858 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006859 MappableExprsHandler::MapValuesArrayTy &Pointers,
6860 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006861 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6862 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006863 auto &CGM = CGF.CGM;
6864 auto &Ctx = CGF.getContext();
6865
Samuel Antaocc10b852016-07-28 14:23:26 +00006866 // Reset the array information.
6867 Info.clearArrayInfo();
6868 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006869
Samuel Antaocc10b852016-07-28 14:23:26 +00006870 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006871 // Detect if we have any capture size requiring runtime evaluation of the
6872 // size so that a constant array could be eventually used.
6873 bool hasRuntimeEvaluationCaptureSize = false;
6874 for (auto *S : Sizes)
6875 if (!isa<llvm::Constant>(S)) {
6876 hasRuntimeEvaluationCaptureSize = true;
6877 break;
6878 }
6879
Samuel Antaocc10b852016-07-28 14:23:26 +00006880 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006881 QualType PointerArrayType =
6882 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6883 /*IndexTypeQuals=*/0);
6884
Samuel Antaocc10b852016-07-28 14:23:26 +00006885 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006886 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006887 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006888 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6889
6890 // If we don't have any VLA types or other types that require runtime
6891 // evaluation, we can use a constant array for the map sizes, otherwise we
6892 // need to fill up the arrays as we do for the pointers.
6893 if (hasRuntimeEvaluationCaptureSize) {
6894 QualType SizeArrayType = Ctx.getConstantArrayType(
6895 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6896 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006897 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006898 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6899 } else {
6900 // We expect all the sizes to be constant, so we collect them to create
6901 // a constant array.
6902 SmallVector<llvm::Constant *, 16> ConstSizes;
6903 for (auto S : Sizes)
6904 ConstSizes.push_back(cast<llvm::Constant>(S));
6905
6906 auto *SizesArrayInit = llvm::ConstantArray::get(
6907 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6908 auto *SizesArrayGbl = new llvm::GlobalVariable(
6909 CGM.getModule(), SizesArrayInit->getType(),
6910 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6911 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006912 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006913 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006914 }
6915
6916 // The map types are always constant so we don't need to generate code to
6917 // fill arrays. Instead, we create an array constant.
6918 llvm::Constant *MapTypesArrayInit =
6919 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6920 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6921 CGM.getModule(), MapTypesArrayInit->getType(),
6922 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6923 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006924 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006925 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006926
Samuel Antaocc10b852016-07-28 14:23:26 +00006927 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6928 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006929 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006930 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6931 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006932 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6933 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006934 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6935 CGF.Builder.CreateStore(BPVal, BPAddr);
6936
Samuel Antaocc10b852016-07-28 14:23:26 +00006937 if (Info.requiresDevicePointerInfo())
6938 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6939 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6940
Samuel Antaodf158d52016-04-27 22:58:19 +00006941 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006942 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006943 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6944 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006945 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6946 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006947 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6948 CGF.Builder.CreateStore(PVal, PAddr);
6949
6950 if (hasRuntimeEvaluationCaptureSize) {
6951 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006952 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6953 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006954 /*Idx0=*/0,
6955 /*Idx1=*/i);
6956 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6957 CGF.Builder.CreateStore(
6958 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6959 SAddr);
6960 }
6961 }
6962 }
6963}
6964/// \brief Emit the arguments to be passed to the runtime library based on the
6965/// arrays of pointers, sizes and map types.
6966static void emitOffloadingArraysArgument(
6967 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6968 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006969 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006970 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006971 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006972 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006973 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6974 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006975 /*Idx0=*/0, /*Idx1=*/0);
6976 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006977 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6978 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006979 /*Idx0=*/0,
6980 /*Idx1=*/0);
6981 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006982 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006983 /*Idx0=*/0, /*Idx1=*/0);
6984 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00006985 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00006986 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006987 /*Idx0=*/0,
6988 /*Idx1=*/0);
6989 } else {
6990 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6991 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6992 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6993 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00006994 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00006995 }
Samuel Antao86ace552016-04-27 22:40:57 +00006996}
6997
Samuel Antaobed3c462015-10-02 16:14:20 +00006998void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6999 const OMPExecutableDirective &D,
7000 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007001 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00007002 const Expr *IfCond, const Expr *Device,
7003 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007004 if (!CGF.HaveInsertPoint())
7005 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007006
Samuel Antaoee8fb302016-01-06 13:42:12 +00007007 assert(OutlinedFn && "Invalid outlined function!");
7008
Samuel Antao86ace552016-04-27 22:40:57 +00007009 // Fill up the arrays with all the captured variables.
7010 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00007011 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00007012 MappableExprsHandler::MapValuesArrayTy Pointers;
7013 MappableExprsHandler::MapValuesArrayTy Sizes;
7014 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00007015
Samuel Antaocc10b852016-07-28 14:23:26 +00007016 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00007017 MappableExprsHandler::MapValuesArrayTy CurPointers;
7018 MappableExprsHandler::MapValuesArrayTy CurSizes;
7019 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7020
Samuel Antaod486f842016-05-26 16:53:38 +00007021 // Get mappable expression information.
7022 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00007023
7024 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
7025 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00007026 auto CV = CapturedVars.begin();
7027 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7028 CE = CS.capture_end();
7029 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00007030 CurBasePointers.clear();
7031 CurPointers.clear();
7032 CurSizes.clear();
7033 CurMapTypes.clear();
7034
7035 // VLA sizes are passed to the outlined region by copy and do not have map
7036 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00007037 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00007038 CurBasePointers.push_back(*CV);
7039 CurPointers.push_back(*CV);
7040 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007041 // Copy to the device as an argument. No need to retrieve it.
George Rokos065755d2017-11-07 18:27:04 +00007042 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7043 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
Samuel Antaobed3c462015-10-02 16:14:20 +00007044 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00007045 // If we have any information in the map clause, we use it, otherwise we
7046 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00007047 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007048 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00007049 if (CurBasePointers.empty())
7050 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7051 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00007052 }
Samuel Antao86ace552016-04-27 22:40:57 +00007053 // We expect to have at least an element of information for this capture.
7054 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
7055 assert(CurBasePointers.size() == CurPointers.size() &&
7056 CurBasePointers.size() == CurSizes.size() &&
7057 CurBasePointers.size() == CurMapTypes.size() &&
7058 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007059
Samuel Antao86ace552016-04-27 22:40:57 +00007060 // The kernel args are always the first elements of the base pointers
7061 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00007062 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00007063 // We need to append the results of this capture to what we already have.
7064 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7065 Pointers.append(CurPointers.begin(), CurPointers.end());
7066 Sizes.append(CurSizes.begin(), CurSizes.end());
7067 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00007068 }
7069
Samuel Antaobed3c462015-10-02 16:14:20 +00007070 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007071 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
7072 OutlinedFn, OutlinedFnID, &D,
7073 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007074 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00007075 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007076 TargetDataInfo Info;
7077 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7078 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7079 Info.PointersArray, Info.SizesArray,
7080 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00007081
7082 // On top of the arrays that were filled up, the target offloading call
7083 // takes as arguments the device id as well as the host pointer. The host
7084 // pointer is used by the runtime library to identify the current target
7085 // region, so it only has to be unique and not necessarily point to
7086 // anything. It could be the pointer to the outlined function that
7087 // implements the target region, but we aren't using that so that the
7088 // compiler doesn't need to keep that, and could therefore inline the host
7089 // function if proven worthwhile during optimization.
7090
Samuel Antaoee8fb302016-01-06 13:42:12 +00007091 // From this point on, we need to have an ID of the target region defined.
7092 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007093
7094 // Emit device ID if any.
7095 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007096 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007097 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007098 CGF.Int64Ty, /*isSigned=*/true);
7099 } else {
7100 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7101 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007102
Samuel Antaodf158d52016-04-27 22:58:19 +00007103 // Emit the number of elements in the offloading arrays.
7104 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7105
Samuel Antaob68e2db2016-03-03 16:20:23 +00007106 // Return value of the runtime offloading call.
7107 llvm::Value *Return;
7108
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007109 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
7110 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007111
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007112 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007113 // The target region is an outlined function launched by the runtime
7114 // via calls __tgt_target() or __tgt_target_teams().
7115 //
7116 // __tgt_target() launches a target region with one team and one thread,
7117 // executing a serial region. This master thread may in turn launch
7118 // more threads within its team upon encountering a parallel region,
7119 // however, no additional teams can be launched on the device.
7120 //
7121 // __tgt_target_teams() launches a target region with one or more teams,
7122 // each with one or more threads. This call is required for target
7123 // constructs such as:
7124 // 'target teams'
7125 // 'target' / 'teams'
7126 // 'target teams distribute parallel for'
7127 // 'target parallel'
7128 // and so on.
7129 //
7130 // Note that on the host and CPU targets, the runtime implementation of
7131 // these calls simply call the outlined function without forking threads.
7132 // The outlined functions themselves have runtime calls to
7133 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7134 // the compiler in emitTeamsCall() and emitParallelCall().
7135 //
7136 // In contrast, on the NVPTX target, the implementation of
7137 // __tgt_target_teams() launches a GPU kernel with the requested number
7138 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007139 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007140 // If we have NumTeams defined this means that we have an enclosed teams
7141 // region. Therefore we also expect to have NumThreads defined. These two
7142 // values should be defined in the presence of a teams directive,
7143 // regardless of having any clauses associated. If the user is using teams
7144 // but no clauses, these two values will be the default that should be
7145 // passed to the runtime library - a 32-bit integer with the value zero.
7146 assert(NumThreads && "Thread limit expression should be available along "
7147 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007148 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007149 DeviceID, OutlinedFnID,
7150 PointerNum, Info.BasePointersArray,
7151 Info.PointersArray, Info.SizesArray,
7152 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007153 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007154 Return = CGF.EmitRuntimeCall(
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007155 RT.createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7156 : OMPRTL__tgt_target_teams),
7157 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007158 } else {
7159 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007160 DeviceID, OutlinedFnID,
7161 PointerNum, Info.BasePointersArray,
7162 Info.PointersArray, Info.SizesArray,
7163 Info.MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007164 Return = CGF.EmitRuntimeCall(
7165 RT.createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7166 : OMPRTL__tgt_target),
7167 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007168 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007169
Alexey Bataev2a007e02017-10-02 14:20:58 +00007170 // Check the error code and execute the host version if required.
7171 llvm::BasicBlock *OffloadFailedBlock =
7172 CGF.createBasicBlock("omp_offload.failed");
7173 llvm::BasicBlock *OffloadContBlock =
7174 CGF.createBasicBlock("omp_offload.cont");
7175 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7176 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7177
7178 CGF.EmitBlock(OffloadFailedBlock);
7179 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7180 CGF.EmitBranch(OffloadContBlock);
7181
7182 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007183 };
7184
Samuel Antaoee8fb302016-01-06 13:42:12 +00007185 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007186 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7187 PrePostActionTy &) {
7188 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7189 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007190 };
7191
7192 // If we have a target function ID it means that we need to support
7193 // offloading, otherwise, just execute on the host. We need to execute on host
7194 // regardless of the conditional in the if clause if, e.g., the user do not
7195 // specify target triples.
7196 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007197 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007198 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007199 else {
7200 RegionCodeGenTy ThenRCG(ThenGen);
7201 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007202 }
7203 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007204 RegionCodeGenTy ElseRCG(ElseGen);
7205 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007206 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007207}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007208
7209void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7210 StringRef ParentName) {
7211 if (!S)
7212 return;
7213
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007214 // Codegen OMP target directives that offload compute to the device.
7215 bool requiresDeviceCodegen =
7216 isa<OMPExecutableDirective>(S) &&
7217 isOpenMPTargetExecutionDirective(
7218 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007219
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007220 if (requiresDeviceCodegen) {
7221 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007222 unsigned DeviceID;
7223 unsigned FileID;
7224 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007225 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007226 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007227
7228 // Is this a target region that should not be emitted as an entry point? If
7229 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007230 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7231 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007232 return;
7233
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007234 switch (S->getStmtClass()) {
7235 case Stmt::OMPTargetDirectiveClass:
7236 CodeGenFunction::EmitOMPTargetDeviceFunction(
7237 CGM, ParentName, cast<OMPTargetDirective>(*S));
7238 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007239 case Stmt::OMPTargetParallelDirectiveClass:
7240 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7241 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7242 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007243 case Stmt::OMPTargetTeamsDirectiveClass:
7244 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7245 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7246 break;
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007247 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
7248 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
7249 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(*S));
7250 break;
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007251 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
7252 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
7253 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(*S));
7254 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007255 case Stmt::OMPTargetParallelForDirectiveClass:
7256 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7257 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7258 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007259 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7260 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7261 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7262 break;
Alexey Bataevf8365372017-11-17 17:57:25 +00007263 case Stmt::OMPTargetSimdDirectiveClass:
7264 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7265 CGM, ParentName, cast<OMPTargetSimdDirective>(*S));
7266 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007267 default:
7268 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7269 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007270 return;
7271 }
7272
7273 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007274 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007275 return;
7276
7277 scanForTargetRegionsFunctions(
7278 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7279 ParentName);
7280 return;
7281 }
7282
7283 // If this is a lambda function, look into its body.
7284 if (auto *L = dyn_cast<LambdaExpr>(S))
7285 S = L->getBody();
7286
7287 // Keep looking for target regions recursively.
7288 for (auto *II : S->children())
7289 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007290}
7291
7292bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7293 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7294
7295 // If emitting code for the host, we do not process FD here. Instead we do
7296 // the normal code generation.
7297 if (!CGM.getLangOpts().OpenMPIsDevice)
7298 return false;
7299
7300 // Try to detect target regions in the function.
7301 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7302
Samuel Antao4b75b872016-12-12 19:26:31 +00007303 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007304 // scanning. Therefore, we signal that this function is completely dealt
7305 // with.
7306 return true;
7307}
7308
7309bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7310 if (!CGM.getLangOpts().OpenMPIsDevice)
7311 return false;
7312
7313 // Check if there are Ctors/Dtors in this declaration and look for target
7314 // regions in it. We use the complete variant to produce the kernel name
7315 // mangling.
7316 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7317 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7318 for (auto *Ctor : RD->ctors()) {
7319 StringRef ParentName =
7320 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7321 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7322 }
7323 auto *Dtor = RD->getDestructor();
7324 if (Dtor) {
7325 StringRef ParentName =
7326 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7327 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7328 }
7329 }
7330
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007331 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007332 // implemented yet). Therefore we signal that GD was processed in this case.
7333 return true;
7334}
7335
7336bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7337 auto *VD = GD.getDecl();
7338 if (isa<FunctionDecl>(VD))
7339 return emitTargetFunctions(GD);
7340
7341 return emitTargetGlobalVariable(GD);
7342}
7343
7344llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7345 // If we have offloading in the current module, we need to emit the entries
7346 // now and register the offloading descriptor.
7347 createOffloadEntriesAndInfoMetadata();
7348
7349 // Create and register the offloading binary descriptors. This is the main
7350 // entity that captures all the information about offloading in the current
7351 // compilation unit.
7352 return createOffloadingBinaryDescriptorRegistration();
7353}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007354
7355void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7356 const OMPExecutableDirective &D,
7357 SourceLocation Loc,
7358 llvm::Value *OutlinedFn,
7359 ArrayRef<llvm::Value *> CapturedVars) {
7360 if (!CGF.HaveInsertPoint())
7361 return;
7362
7363 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7364 CodeGenFunction::RunCleanupsScope Scope(CGF);
7365
7366 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7367 llvm::Value *Args[] = {
7368 RTLoc,
7369 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7370 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7371 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7372 RealArgs.append(std::begin(Args), std::end(Args));
7373 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7374
7375 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7376 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7377}
7378
7379void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007380 const Expr *NumTeams,
7381 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007382 SourceLocation Loc) {
7383 if (!CGF.HaveInsertPoint())
7384 return;
7385
7386 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7387
Carlo Bertollic6872252016-04-04 15:55:02 +00007388 llvm::Value *NumTeamsVal =
7389 (NumTeams)
7390 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7391 CGF.CGM.Int32Ty, /* isSigned = */ true)
7392 : CGF.Builder.getInt32(0);
7393
7394 llvm::Value *ThreadLimitVal =
7395 (ThreadLimit)
7396 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7397 CGF.CGM.Int32Ty, /* isSigned = */ true)
7398 : CGF.Builder.getInt32(0);
7399
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007400 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007401 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7402 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007403 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7404 PushNumTeamsArgs);
7405}
Samuel Antaodf158d52016-04-27 22:58:19 +00007406
Samuel Antaocc10b852016-07-28 14:23:26 +00007407void CGOpenMPRuntime::emitTargetDataCalls(
7408 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7409 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007410 if (!CGF.HaveInsertPoint())
7411 return;
7412
Samuel Antaocc10b852016-07-28 14:23:26 +00007413 // Action used to replace the default codegen action and turn privatization
7414 // off.
7415 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007416
7417 // Generate the code for the opening of the data environment. Capture all the
7418 // arguments of the runtime call by reference because they are used in the
7419 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007420 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7421 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007422 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007423 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007424 MappableExprsHandler::MapValuesArrayTy Pointers;
7425 MappableExprsHandler::MapValuesArrayTy Sizes;
7426 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7427
7428 // Get map clause information.
7429 MappableExprsHandler MCHandler(D, CGF);
7430 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007431
7432 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007433 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007434
7435 llvm::Value *BasePointersArrayArg = nullptr;
7436 llvm::Value *PointersArrayArg = nullptr;
7437 llvm::Value *SizesArrayArg = nullptr;
7438 llvm::Value *MapTypesArrayArg = nullptr;
7439 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007440 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007441
7442 // Emit device ID if any.
7443 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007444 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007445 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007446 CGF.Int64Ty, /*isSigned=*/true);
7447 } else {
7448 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7449 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007450
7451 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007452 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007453
7454 llvm::Value *OffloadingArgs[] = {
7455 DeviceID, PointerNum, BasePointersArrayArg,
7456 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7457 auto &RT = CGF.CGM.getOpenMPRuntime();
7458 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7459 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007460
7461 // If device pointer privatization is required, emit the body of the region
7462 // here. It will have to be duplicated: with and without privatization.
7463 if (!Info.CaptureDeviceAddrMap.empty())
7464 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007465 };
7466
7467 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007468 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007469 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007470
7471 llvm::Value *BasePointersArrayArg = nullptr;
7472 llvm::Value *PointersArrayArg = nullptr;
7473 llvm::Value *SizesArrayArg = nullptr;
7474 llvm::Value *MapTypesArrayArg = nullptr;
7475 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007476 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007477
7478 // Emit device ID if any.
7479 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007480 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007481 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007482 CGF.Int64Ty, /*isSigned=*/true);
7483 } else {
7484 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7485 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007486
7487 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007488 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007489
7490 llvm::Value *OffloadingArgs[] = {
7491 DeviceID, PointerNum, BasePointersArrayArg,
7492 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7493 auto &RT = CGF.CGM.getOpenMPRuntime();
7494 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7495 OffloadingArgs);
7496 };
7497
Samuel Antaocc10b852016-07-28 14:23:26 +00007498 // If we need device pointer privatization, we need to emit the body of the
7499 // region with no privatization in the 'else' branch of the conditional.
7500 // Otherwise, we don't have to do anything.
7501 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7502 PrePostActionTy &) {
7503 if (!Info.CaptureDeviceAddrMap.empty()) {
7504 CodeGen.setAction(NoPrivAction);
7505 CodeGen(CGF);
7506 }
7507 };
7508
7509 // We don't have to do anything to close the region if the if clause evaluates
7510 // to false.
7511 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007512
7513 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007514 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007515 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007516 RegionCodeGenTy RCG(BeginThenGen);
7517 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007518 }
7519
Samuel Antaocc10b852016-07-28 14:23:26 +00007520 // If we don't require privatization of device pointers, we emit the body in
7521 // between the runtime calls. This avoids duplicating the body code.
7522 if (Info.CaptureDeviceAddrMap.empty()) {
7523 CodeGen.setAction(NoPrivAction);
7524 CodeGen(CGF);
7525 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007526
7527 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007528 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007529 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007530 RegionCodeGenTy RCG(EndThenGen);
7531 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007532 }
7533}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007534
Samuel Antao8d2d7302016-05-26 18:30:22 +00007535void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007536 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7537 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007538 if (!CGF.HaveInsertPoint())
7539 return;
7540
Samuel Antao8dd66282016-04-27 23:14:30 +00007541 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007542 isa<OMPTargetExitDataDirective>(D) ||
7543 isa<OMPTargetUpdateDirective>(D)) &&
7544 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007545
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007546 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007547 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007548 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007549 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007550 MappableExprsHandler::MapValuesArrayTy Pointers;
7551 MappableExprsHandler::MapValuesArrayTy Sizes;
7552 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7553
7554 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007555 MappableExprsHandler MEHandler(D, CGF);
7556 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007557
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007558 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007559 TargetDataInfo Info;
7560 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7561 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7562 Info.PointersArray, Info.SizesArray,
7563 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007564
7565 // Emit device ID if any.
7566 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007567 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007568 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007569 CGF.Int64Ty, /*isSigned=*/true);
7570 } else {
7571 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7572 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007573
7574 // Emit the number of elements in the offloading arrays.
7575 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7576
7577 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007578 DeviceID, PointerNum, Info.BasePointersArray,
7579 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007580
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007581 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007582 // Select the right runtime function call for each expected standalone
7583 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007584 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007585 OpenMPRTLFunction RTLFn;
7586 switch (D.getDirectiveKind()) {
7587 default:
7588 llvm_unreachable("Unexpected standalone target data directive.");
7589 break;
7590 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007591 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
7592 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007593 break;
7594 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007595 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
7596 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007597 break;
7598 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007599 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
7600 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007601 break;
7602 }
7603 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007604 };
7605
7606 // In the event we get an if clause, we don't have to take any action on the
7607 // else side.
7608 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7609
7610 if (IfCond) {
7611 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7612 } else {
7613 RegionCodeGenTy ThenGenRCG(ThenGen);
7614 ThenGenRCG(CGF);
7615 }
7616}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007617
7618namespace {
7619 /// Kind of parameter in a function with 'declare simd' directive.
7620 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7621 /// Attribute set of the parameter.
7622 struct ParamAttrTy {
7623 ParamKindTy Kind = Vector;
7624 llvm::APSInt StrideOrArg;
7625 llvm::APSInt Alignment;
7626 };
7627} // namespace
7628
7629static unsigned evaluateCDTSize(const FunctionDecl *FD,
7630 ArrayRef<ParamAttrTy> ParamAttrs) {
7631 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7632 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7633 // of that clause. The VLEN value must be power of 2.
7634 // In other case the notion of the function`s "characteristic data type" (CDT)
7635 // is used to compute the vector length.
7636 // CDT is defined in the following order:
7637 // a) For non-void function, the CDT is the return type.
7638 // b) If the function has any non-uniform, non-linear parameters, then the
7639 // CDT is the type of the first such parameter.
7640 // c) If the CDT determined by a) or b) above is struct, union, or class
7641 // type which is pass-by-value (except for the type that maps to the
7642 // built-in complex data type), the characteristic data type is int.
7643 // d) If none of the above three cases is applicable, the CDT is int.
7644 // The VLEN is then determined based on the CDT and the size of vector
7645 // register of that ISA for which current vector version is generated. The
7646 // VLEN is computed using the formula below:
7647 // VLEN = sizeof(vector_register) / sizeof(CDT),
7648 // where vector register size specified in section 3.2.1 Registers and the
7649 // Stack Frame of original AMD64 ABI document.
7650 QualType RetType = FD->getReturnType();
7651 if (RetType.isNull())
7652 return 0;
7653 ASTContext &C = FD->getASTContext();
7654 QualType CDT;
7655 if (!RetType.isNull() && !RetType->isVoidType())
7656 CDT = RetType;
7657 else {
7658 unsigned Offset = 0;
7659 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7660 if (ParamAttrs[Offset].Kind == Vector)
7661 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7662 ++Offset;
7663 }
7664 if (CDT.isNull()) {
7665 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7666 if (ParamAttrs[I + Offset].Kind == Vector) {
7667 CDT = FD->getParamDecl(I)->getType();
7668 break;
7669 }
7670 }
7671 }
7672 }
7673 if (CDT.isNull())
7674 CDT = C.IntTy;
7675 CDT = CDT->getCanonicalTypeUnqualified();
7676 if (CDT->isRecordType() || CDT->isUnionType())
7677 CDT = C.IntTy;
7678 return C.getTypeSize(CDT);
7679}
7680
7681static void
7682emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007683 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007684 ArrayRef<ParamAttrTy> ParamAttrs,
7685 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7686 struct ISADataTy {
7687 char ISA;
7688 unsigned VecRegSize;
7689 };
7690 ISADataTy ISAData[] = {
7691 {
7692 'b', 128
7693 }, // SSE
7694 {
7695 'c', 256
7696 }, // AVX
7697 {
7698 'd', 256
7699 }, // AVX2
7700 {
7701 'e', 512
7702 }, // AVX512
7703 };
7704 llvm::SmallVector<char, 2> Masked;
7705 switch (State) {
7706 case OMPDeclareSimdDeclAttr::BS_Undefined:
7707 Masked.push_back('N');
7708 Masked.push_back('M');
7709 break;
7710 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7711 Masked.push_back('N');
7712 break;
7713 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7714 Masked.push_back('M');
7715 break;
7716 }
7717 for (auto Mask : Masked) {
7718 for (auto &Data : ISAData) {
7719 SmallString<256> Buffer;
7720 llvm::raw_svector_ostream Out(Buffer);
7721 Out << "_ZGV" << Data.ISA << Mask;
7722 if (!VLENVal) {
7723 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7724 evaluateCDTSize(FD, ParamAttrs));
7725 } else
7726 Out << VLENVal;
7727 for (auto &ParamAttr : ParamAttrs) {
7728 switch (ParamAttr.Kind){
7729 case LinearWithVarStride:
7730 Out << 's' << ParamAttr.StrideOrArg;
7731 break;
7732 case Linear:
7733 Out << 'l';
7734 if (!!ParamAttr.StrideOrArg)
7735 Out << ParamAttr.StrideOrArg;
7736 break;
7737 case Uniform:
7738 Out << 'u';
7739 break;
7740 case Vector:
7741 Out << 'v';
7742 break;
7743 }
7744 if (!!ParamAttr.Alignment)
7745 Out << 'a' << ParamAttr.Alignment;
7746 }
7747 Out << '_' << Fn->getName();
7748 Fn->addFnAttr(Out.str());
7749 }
7750 }
7751}
7752
7753void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7754 llvm::Function *Fn) {
7755 ASTContext &C = CGM.getContext();
7756 FD = FD->getCanonicalDecl();
7757 // Map params to their positions in function decl.
7758 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7759 if (isa<CXXMethodDecl>(FD))
7760 ParamPositions.insert({FD, 0});
7761 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007762 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007763 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7764 ++ParamPos;
7765 }
7766 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7767 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7768 // Mark uniform parameters.
7769 for (auto *E : Attr->uniforms()) {
7770 E = E->IgnoreParenImpCasts();
7771 unsigned Pos;
7772 if (isa<CXXThisExpr>(E))
7773 Pos = ParamPositions[FD];
7774 else {
7775 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7776 ->getCanonicalDecl();
7777 Pos = ParamPositions[PVD];
7778 }
7779 ParamAttrs[Pos].Kind = Uniform;
7780 }
7781 // Get alignment info.
7782 auto NI = Attr->alignments_begin();
7783 for (auto *E : Attr->aligneds()) {
7784 E = E->IgnoreParenImpCasts();
7785 unsigned Pos;
7786 QualType ParmTy;
7787 if (isa<CXXThisExpr>(E)) {
7788 Pos = ParamPositions[FD];
7789 ParmTy = E->getType();
7790 } else {
7791 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7792 ->getCanonicalDecl();
7793 Pos = ParamPositions[PVD];
7794 ParmTy = PVD->getType();
7795 }
7796 ParamAttrs[Pos].Alignment =
7797 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7798 : llvm::APSInt::getUnsigned(
7799 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7800 .getQuantity());
7801 ++NI;
7802 }
7803 // Mark linear parameters.
7804 auto SI = Attr->steps_begin();
7805 auto MI = Attr->modifiers_begin();
7806 for (auto *E : Attr->linears()) {
7807 E = E->IgnoreParenImpCasts();
7808 unsigned Pos;
7809 if (isa<CXXThisExpr>(E))
7810 Pos = ParamPositions[FD];
7811 else {
7812 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7813 ->getCanonicalDecl();
7814 Pos = ParamPositions[PVD];
7815 }
7816 auto &ParamAttr = ParamAttrs[Pos];
7817 ParamAttr.Kind = Linear;
7818 if (*SI) {
7819 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7820 Expr::SE_AllowSideEffects)) {
7821 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7822 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7823 ParamAttr.Kind = LinearWithVarStride;
7824 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7825 ParamPositions[StridePVD->getCanonicalDecl()]);
7826 }
7827 }
7828 }
7829 }
7830 ++SI;
7831 ++MI;
7832 }
7833 llvm::APSInt VLENVal;
7834 if (const Expr *VLEN = Attr->getSimdlen())
7835 VLENVal = VLEN->EvaluateKnownConstInt(C);
7836 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7837 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7838 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7839 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7840 }
7841}
Alexey Bataev8b427062016-05-25 12:36:08 +00007842
7843namespace {
7844/// Cleanup action for doacross support.
7845class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7846public:
7847 static const int DoacrossFinArgs = 2;
7848
7849private:
7850 llvm::Value *RTLFn;
7851 llvm::Value *Args[DoacrossFinArgs];
7852
7853public:
7854 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7855 : RTLFn(RTLFn) {
7856 assert(CallArgs.size() == DoacrossFinArgs);
7857 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7858 }
7859 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7860 if (!CGF.HaveInsertPoint())
7861 return;
7862 CGF.EmitRuntimeCall(RTLFn, Args);
7863 }
7864};
7865} // namespace
7866
7867void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7868 const OMPLoopDirective &D) {
7869 if (!CGF.HaveInsertPoint())
7870 return;
7871
7872 ASTContext &C = CGM.getContext();
7873 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7874 RecordDecl *RD;
7875 if (KmpDimTy.isNull()) {
7876 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7877 // kmp_int64 lo; // lower
7878 // kmp_int64 up; // upper
7879 // kmp_int64 st; // stride
7880 // };
7881 RD = C.buildImplicitRecord("kmp_dim");
7882 RD->startDefinition();
7883 addFieldToRecordDecl(C, RD, Int64Ty);
7884 addFieldToRecordDecl(C, RD, Int64Ty);
7885 addFieldToRecordDecl(C, RD, Int64Ty);
7886 RD->completeDefinition();
7887 KmpDimTy = C.getRecordType(RD);
7888 } else
7889 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7890
7891 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7892 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7893 enum { LowerFD = 0, UpperFD, StrideFD };
7894 // Fill dims with data.
7895 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7896 // dims.upper = num_iterations;
7897 LValue UpperLVal =
7898 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7899 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7900 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7901 Int64Ty, D.getNumIterations()->getExprLoc());
7902 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7903 // dims.stride = 1;
7904 LValue StrideLVal =
7905 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7906 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7907 StrideLVal);
7908
7909 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7910 // kmp_int32 num_dims, struct kmp_dim * dims);
7911 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7912 getThreadID(CGF, D.getLocStart()),
7913 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7914 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7915 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7916
7917 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7918 CGF.EmitRuntimeCall(RTLFn, Args);
7919 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7920 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7921 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7922 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7923 llvm::makeArrayRef(FiniArgs));
7924}
7925
7926void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7927 const OMPDependClause *C) {
7928 QualType Int64Ty =
7929 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7930 const Expr *CounterVal = C->getCounterValue();
7931 assert(CounterVal);
7932 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7933 CounterVal->getType(), Int64Ty,
7934 CounterVal->getExprLoc());
7935 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7936 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7937 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7938 getThreadID(CGF, C->getLocStart()),
7939 CntAddr.getPointer()};
7940 llvm::Value *RTLFn;
7941 if (C->getDependencyKind() == OMPC_DEPEND_source)
7942 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7943 else {
7944 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7945 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7946 }
7947 CGF.EmitRuntimeCall(RTLFn, Args);
7948}
7949
Alexey Bataev3c595a62017-08-14 15:01:03 +00007950void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7951 ArrayRef<llvm::Value *> Args,
7952 SourceLocation Loc) const {
7953 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7954
7955 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007956 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007957 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007958 return;
7959 }
7960 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007961 CGF.EmitRuntimeCall(Callee, Args);
7962}
7963
7964void CGOpenMPRuntime::emitOutlinedFunctionCall(
7965 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7966 ArrayRef<llvm::Value *> Args) const {
7967 assert(Loc.isValid() && "Outlined function call location must be valid.");
7968 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007969}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007970
7971Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7972 const VarDecl *NativeParam,
7973 const VarDecl *TargetParam) const {
7974 return CGF.GetAddrOfLocalVar(NativeParam);
7975}