blob: 0a798b89030d32cfe40c1046443df055f5624ac7 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
195 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Alexey Bataev311a9282017-10-12 13:51:32 +0000268 /// \brief Get an LValue for the current ThreadID variable.
269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct");
273 }
274
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000275 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000276 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 llvm_unreachable("No helper name for inlined OpenMP construct");
280 }
281
Alexey Bataev48591dd2016-04-20 04:01:36 +0000282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
Alexey Bataev48591dd2016-04-20 04:01:36 +0000294 ~CGOpenMPInlinedRegionInfo() override = default;
295
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000296private:
297 /// \brief CodeGen info about outer OpenMP region.
298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000300};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000301
Samuel Antaobed3c462015-10-02 16:14:20 +0000302/// \brief API for captured statement code generation in OpenMP target
303/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 /// \brief This is unused for target regions because each starts executing
316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
319 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000320 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000326
327private:
328 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000329};
330
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000332 llvm_unreachable("No codegen for expressions");
333}
334/// \brief API for generation of expressions captured in a innermost OpenMP
335/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
346 for (auto &C : CS.captures()) {
347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
354 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
357 SourceLocation());
358 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
359 return CGF.EmitLValue(&DRE).getAddress();
360 });
361 }
362 (void)PrivScope.Privatize();
363 }
364
365 /// \brief Lookup the captured field decl for a variable.
366 const FieldDecl *lookup(const VarDecl *VD) const override {
367 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
368 return FD;
369 return nullptr;
370 }
371
372 /// \brief Emit the captured statement body.
373 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
374 llvm_unreachable("No body for expressions");
375 }
376
377 /// \brief Get a variable or parameter for storing global thread id
378 /// inside OpenMP construct.
379 const VarDecl *getThreadIDVariable() const override {
380 llvm_unreachable("No thread id for expressions");
381 }
382
383 /// \brief Get the name of the capture helper.
384 StringRef getHelperName() const override {
385 llvm_unreachable("No helper name for expressions");
386 }
387
388 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
389
390private:
391 /// Private scope to capture global variables.
392 CodeGenFunction::OMPPrivateScope PrivScope;
393};
394
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000395/// \brief RAII for emitting code of OpenMP constructs.
396class InlinedOpenMPRegionRAII {
397 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000398 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
399 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400
401public:
402 /// \brief Constructs region for combined constructs.
403 /// \param CodeGen Code generation sequence for combined directives. Includes
404 /// a list of functions used for code generation of implicitly inlined
405 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000406 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000407 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 : CGF(CGF) {
409 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000410 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
411 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
413 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
414 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000415 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000416
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 ~InlinedOpenMPRegionRAII() {
418 // Restore original CapturedStmtInfo only if we're done with code emission.
419 auto *OldCSI =
420 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
421 delete CGF.CapturedStmtInfo;
422 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000423 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
424 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000425 }
426};
427
Alexey Bataev50b3c952016-02-19 10:38:26 +0000428/// \brief Values for bit flags used in the ident_t to describe the fields.
429/// All enumeric elements are named and described in accordance with the code
430/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000431enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432 /// \brief Use trampoline for internal microtask.
433 OMP_IDENT_IMD = 0x01,
434 /// \brief Use c-style ident structure.
435 OMP_IDENT_KMPC = 0x02,
436 /// \brief Atomic reduction option for kmpc_reduce.
437 OMP_ATOMIC_REDUCE = 0x10,
438 /// \brief Explicit 'barrier' directive.
439 OMP_IDENT_BARRIER_EXPL = 0x20,
440 /// \brief Implicit barrier in code.
441 OMP_IDENT_BARRIER_IMPL = 0x40,
442 /// \brief Implicit barrier in 'for' directive.
443 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
444 /// \brief Implicit barrier in 'sections' directive.
445 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
446 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000447 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
448 /// Call of __kmp_for_static_init for static loop.
449 OMP_IDENT_WORK_LOOP = 0x200,
450 /// Call of __kmp_for_static_init for sections.
451 OMP_IDENT_WORK_SECTIONS = 0x400,
452 /// Call of __kmp_for_static_init for distribute.
453 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
454 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000455};
456
457/// \brief Describes ident structure that describes a source location.
458/// All descriptions are taken from
459/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
460/// Original structure:
461/// typedef struct ident {
462/// kmp_int32 reserved_1; /**< might be used in Fortran;
463/// see above */
464/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
465/// KMP_IDENT_KMPC identifies this union
466/// member */
467/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
468/// see above */
469///#if USE_ITT_BUILD
470/// /* but currently used for storing
471/// region-specific ITT */
472/// /* contextual information. */
473///#endif /* USE_ITT_BUILD */
474/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
475/// C++ */
476/// char const *psource; /**< String describing the source location.
477/// The string is composed of semi-colon separated
478// fields which describe the source file,
479/// the function and a pair of line numbers that
480/// delimit the construct.
481/// */
482/// } ident_t;
483enum IdentFieldIndex {
484 /// \brief might be used in Fortran
485 IdentField_Reserved_1,
486 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
487 IdentField_Flags,
488 /// \brief Not really used in Fortran any more
489 IdentField_Reserved_2,
490 /// \brief Source[4] in Fortran, do not use for C++
491 IdentField_Reserved_3,
492 /// \brief String describing the source location. The string is composed of
493 /// semi-colon separated fields which describe the source file, the function
494 /// and a pair of line numbers that delimit the construct.
495 IdentField_PSource
496};
497
498/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
499/// the enum sched_type in kmp.h).
500enum OpenMPSchedType {
501 /// \brief Lower bound for default (unordered) versions.
502 OMP_sch_lower = 32,
503 OMP_sch_static_chunked = 33,
504 OMP_sch_static = 34,
505 OMP_sch_dynamic_chunked = 35,
506 OMP_sch_guided_chunked = 36,
507 OMP_sch_runtime = 37,
508 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000509 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000510 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000511 /// \brief Lower bound for 'ordered' versions.
512 OMP_ord_lower = 64,
513 OMP_ord_static_chunked = 65,
514 OMP_ord_static = 66,
515 OMP_ord_dynamic_chunked = 67,
516 OMP_ord_guided_chunked = 68,
517 OMP_ord_runtime = 69,
518 OMP_ord_auto = 70,
519 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000520 /// \brief dist_schedule types
521 OMP_dist_sch_static_chunked = 91,
522 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000523 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
524 /// Set if the monotonic schedule modifier was present.
525 OMP_sch_modifier_monotonic = (1 << 29),
526 /// Set if the nonmonotonic schedule modifier was present.
527 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000528};
529
530enum OpenMPRTLFunction {
531 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
532 /// kmpc_micro microtask, ...);
533 OMPRTL__kmpc_fork_call,
534 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
535 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
536 OMPRTL__kmpc_threadprivate_cached,
537 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
538 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
539 OMPRTL__kmpc_threadprivate_register,
540 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
541 OMPRTL__kmpc_global_thread_num,
542 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
543 // kmp_critical_name *crit);
544 OMPRTL__kmpc_critical,
545 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
546 // global_tid, kmp_critical_name *crit, uintptr_t hint);
547 OMPRTL__kmpc_critical_with_hint,
548 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
549 // kmp_critical_name *crit);
550 OMPRTL__kmpc_end_critical,
551 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
552 // global_tid);
553 OMPRTL__kmpc_cancel_barrier,
554 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
555 OMPRTL__kmpc_barrier,
556 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
557 OMPRTL__kmpc_for_static_fini,
558 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
559 // global_tid);
560 OMPRTL__kmpc_serialized_parallel,
561 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 OMPRTL__kmpc_end_serialized_parallel,
564 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
565 // kmp_int32 num_threads);
566 OMPRTL__kmpc_push_num_threads,
567 // Call to void __kmpc_flush(ident_t *loc);
568 OMPRTL__kmpc_flush,
569 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
570 OMPRTL__kmpc_master,
571 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
572 OMPRTL__kmpc_end_master,
573 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
574 // int end_part);
575 OMPRTL__kmpc_omp_taskyield,
576 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_single,
578 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
579 OMPRTL__kmpc_end_single,
580 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
581 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
582 // kmp_routine_entry_t *task_entry);
583 OMPRTL__kmpc_omp_task_alloc,
584 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
585 // new_task);
586 OMPRTL__kmpc_omp_task,
587 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
588 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
589 // kmp_int32 didit);
590 OMPRTL__kmpc_copyprivate,
591 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
592 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
593 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
594 OMPRTL__kmpc_reduce,
595 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
596 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
597 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
598 // *lck);
599 OMPRTL__kmpc_reduce_nowait,
600 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
601 // kmp_critical_name *lck);
602 OMPRTL__kmpc_end_reduce,
603 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
604 // kmp_critical_name *lck);
605 OMPRTL__kmpc_end_reduce_nowait,
606 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
607 // kmp_task_t * new_task);
608 OMPRTL__kmpc_omp_task_begin_if0,
609 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
610 // kmp_task_t * new_task);
611 OMPRTL__kmpc_omp_task_complete_if0,
612 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
613 OMPRTL__kmpc_ordered,
614 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
615 OMPRTL__kmpc_end_ordered,
616 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
617 // global_tid);
618 OMPRTL__kmpc_omp_taskwait,
619 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_taskgroup,
621 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
622 OMPRTL__kmpc_end_taskgroup,
623 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
624 // int proc_bind);
625 OMPRTL__kmpc_push_proc_bind,
626 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
627 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
628 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
629 OMPRTL__kmpc_omp_task_with_deps,
630 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
632 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_wait_deps,
634 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
635 // global_tid, kmp_int32 cncl_kind);
636 OMPRTL__kmpc_cancellationpoint,
637 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
638 // kmp_int32 cncl_kind);
639 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000640 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
641 // kmp_int32 num_teams, kmp_int32 thread_limit);
642 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000643 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
644 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000646 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
647 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
648 // sched, kmp_uint64 grainsize, void *task_dup);
649 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000650 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
651 // num_dims, struct kmp_dim *dims);
652 OMPRTL__kmpc_doacross_init,
653 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
654 OMPRTL__kmpc_doacross_fini,
655 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
656 // *vec);
657 OMPRTL__kmpc_doacross_post,
658 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
659 // *vec);
660 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000661 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
662 // *data);
663 OMPRTL__kmpc_task_reduction_init,
664 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
665 // *d);
666 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000667
668 //
669 // Offloading related calls
670 //
671 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
672 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
673 // *arg_types);
674 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000675 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
676 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
677 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
678 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000679 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
680 OMPRTL__tgt_register_lib,
681 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
682 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000683 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
684 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
685 OMPRTL__tgt_target_data_begin,
686 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
687 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
688 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000689 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
690 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
691 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692};
693
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000694/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
695/// region.
696class CleanupTy final : public EHScopeStack::Cleanup {
697 PrePostActionTy *Action;
698
699public:
700 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
701 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
702 if (!CGF.HaveInsertPoint())
703 return;
704 Action->Exit(CGF);
705 }
706};
707
Hans Wennborg7eb54642015-09-10 17:07:54 +0000708} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000709
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000710void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
711 CodeGenFunction::RunCleanupsScope Scope(CGF);
712 if (PrePostAction) {
713 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
714 Callback(CodeGen, CGF, *PrePostAction);
715 } else {
716 PrePostActionTy Action;
717 Callback(CodeGen, CGF, Action);
718 }
719}
720
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000721/// Check if the combiner is a call to UDR combiner and if it is so return the
722/// UDR decl used for reduction.
723static const OMPDeclareReductionDecl *
724getReductionInit(const Expr *ReductionOp) {
725 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
726 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
727 if (auto *DRE =
728 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
729 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
730 return DRD;
731 return nullptr;
732}
733
734static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
735 const OMPDeclareReductionDecl *DRD,
736 const Expr *InitOp,
737 Address Private, Address Original,
738 QualType Ty) {
739 if (DRD->getInitializer()) {
740 std::pair<llvm::Function *, llvm::Function *> Reduction =
741 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
742 auto *CE = cast<CallExpr>(InitOp);
743 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
744 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
745 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
746 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
747 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
748 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
749 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
750 [=]() -> Address { return Private; });
751 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
752 [=]() -> Address { return Original; });
753 (void)PrivateScope.Privatize();
754 RValue Func = RValue::get(Reduction.second);
755 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
756 CGF.EmitIgnoredExpr(InitOp);
757 } else {
758 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
759 auto *GV = new llvm::GlobalVariable(
760 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
761 llvm::GlobalValue::PrivateLinkage, Init, ".init");
762 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
763 RValue InitRVal;
764 switch (CGF.getEvaluationKind(Ty)) {
765 case TEK_Scalar:
766 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
767 break;
768 case TEK_Complex:
769 InitRVal =
770 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
771 break;
772 case TEK_Aggregate:
773 InitRVal = RValue::getAggregate(LV.getAddress());
774 break;
775 }
776 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
777 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
778 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
779 /*IsInitializer=*/false);
780 }
781}
782
783/// \brief Emit initialization of arrays of complex types.
784/// \param DestAddr Address of the array.
785/// \param Type Type of array.
786/// \param Init Initial expression of array.
787/// \param SrcAddr Address of the original array.
788static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000789 QualType Type, bool EmitDeclareReductionInit,
790 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000791 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000792 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000793 // Perform element-by-element initialization.
794 QualType ElementTy;
795
796 // Drill down to the base element type on both arrays.
797 auto ArrayTy = Type->getAsArrayTypeUnsafe();
798 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
799 DestAddr =
800 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
801 if (DRD)
802 SrcAddr =
803 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
804
805 llvm::Value *SrcBegin = nullptr;
806 if (DRD)
807 SrcBegin = SrcAddr.getPointer();
808 auto DestBegin = DestAddr.getPointer();
809 // Cast from pointer to array type to pointer to single element.
810 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
811 // The basic structure here is a while-do loop.
812 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
813 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
814 auto IsEmpty =
815 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
816 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
817
818 // Enter the loop body, making that address the current address.
819 auto EntryBB = CGF.Builder.GetInsertBlock();
820 CGF.EmitBlock(BodyBB);
821
822 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
823
824 llvm::PHINode *SrcElementPHI = nullptr;
825 Address SrcElementCurrent = Address::invalid();
826 if (DRD) {
827 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
828 "omp.arraycpy.srcElementPast");
829 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
830 SrcElementCurrent =
831 Address(SrcElementPHI,
832 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
833 }
834 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
835 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
836 DestElementPHI->addIncoming(DestBegin, EntryBB);
837 Address DestElementCurrent =
838 Address(DestElementPHI,
839 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
840
841 // Emit copy.
842 {
843 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000844 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000845 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
846 SrcElementCurrent, ElementTy);
847 } else
848 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
849 /*IsInitializer=*/false);
850 }
851
852 if (DRD) {
853 // Shift the address forward by one element.
854 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
855 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
856 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
857 }
858
859 // Shift the address forward by one element.
860 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
861 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
862 // Check whether we've reached the end.
863 auto Done =
864 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
865 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
866 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
867
868 // Done.
869 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
870}
871
872LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000873 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000874}
875
876LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
877 const Expr *E) {
878 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
879 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
880 return LValue();
881}
882
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000883void ReductionCodeGen::emitAggregateInitialization(
884 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
885 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000886 // Emit VarDecl with copy init for arrays.
887 // Get the address of the original variable captured in current
888 // captured region.
889 auto *PrivateVD =
890 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000891 bool EmitDeclareReductionInit =
892 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000893 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000894 EmitDeclareReductionInit,
895 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
896 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000897 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000898}
899
900ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
901 ArrayRef<const Expr *> Privates,
902 ArrayRef<const Expr *> ReductionOps) {
903 ClausesData.reserve(Shareds.size());
904 SharedAddresses.reserve(Shareds.size());
905 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000906 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000907 auto IPriv = Privates.begin();
908 auto IRed = ReductionOps.begin();
909 for (const auto *Ref : Shareds) {
910 ClausesData.emplace_back(Ref, *IPriv, *IRed);
911 std::advance(IPriv, 1);
912 std::advance(IRed, 1);
913 }
914}
915
916void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
917 assert(SharedAddresses.size() == N &&
918 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000919 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
920 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
921 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000922}
923
924void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
925 auto *PrivateVD =
926 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
927 QualType PrivateType = PrivateVD->getType();
928 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000929 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930 Sizes.emplace_back(
931 CGF.getTypeSize(
932 SharedAddresses[N].first.getType().getNonReferenceType()),
933 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000934 return;
935 }
936 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000937 llvm::Value *SizeInChars;
938 llvm::Type *ElemType =
939 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
940 ->getElementType();
941 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 if (AsArraySection) {
943 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
944 SharedAddresses[N].first.getPointer());
945 Size = CGF.Builder.CreateNUWAdd(
946 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000949 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000951 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000953 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 CodeGenFunction::OpaqueValueMapping OpaqueMap(
955 CGF,
956 cast<OpaqueValueExpr>(
957 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
958 RValue::get(Size));
959 CGF.EmitVariablyModifiedType(PrivateType);
960}
961
962void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
963 llvm::Value *Size) {
964 auto *PrivateVD =
965 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
966 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000967 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000968 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000969 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 "items.");
971 return;
972 }
973 CodeGenFunction::OpaqueValueMapping OpaqueMap(
974 CGF,
975 cast<OpaqueValueExpr>(
976 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
977 RValue::get(Size));
978 CGF.EmitVariablyModifiedType(PrivateType);
979}
980
981void ReductionCodeGen::emitInitialization(
982 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
983 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
984 assert(SharedAddresses.size() > N && "No variable was generated");
985 auto *PrivateVD =
986 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
987 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
988 QualType PrivateType = PrivateVD->getType();
989 PrivateAddr = CGF.Builder.CreateElementBitCast(
990 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
991 QualType SharedType = SharedAddresses[N].first.getType();
992 SharedLVal = CGF.MakeAddrLValue(
993 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
994 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +0000995 SharedType, SharedAddresses[N].first.getBaseInfo(),
996 CGF.CGM.getTBAAAccessInfo(SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000997 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1000 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1001 PrivateAddr, SharedLVal.getAddress(),
1002 SharedLVal.getType());
1003 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1004 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1005 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1006 PrivateVD->getType().getQualifiers(),
1007 /*IsInitializer=*/false);
1008 }
1009}
1010
1011bool ReductionCodeGen::needCleanups(unsigned N) {
1012 auto *PrivateVD =
1013 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1014 QualType PrivateType = PrivateVD->getType();
1015 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1016 return DTorKind != QualType::DK_none;
1017}
1018
1019void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1020 Address PrivateAddr) {
1021 auto *PrivateVD =
1022 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1023 QualType PrivateType = PrivateVD->getType();
1024 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1025 if (needCleanups(N)) {
1026 PrivateAddr = CGF.Builder.CreateElementBitCast(
1027 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1028 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1029 }
1030}
1031
1032static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1033 LValue BaseLV) {
1034 BaseTy = BaseTy.getNonReferenceType();
1035 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1036 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1037 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1038 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1039 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001040 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1041 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001042 }
1043 BaseTy = BaseTy->getPointeeType();
1044 }
1045 return CGF.MakeAddrLValue(
1046 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1047 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001048 BaseLV.getType(), BaseLV.getBaseInfo(),
1049 CGF.CGM.getTBAAAccessInfo(BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001050}
1051
1052static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1053 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1054 llvm::Value *Addr) {
1055 Address Tmp = Address::invalid();
1056 Address TopTmp = Address::invalid();
1057 Address MostTopTmp = Address::invalid();
1058 BaseTy = BaseTy.getNonReferenceType();
1059 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1060 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1061 Tmp = CGF.CreateMemTemp(BaseTy);
1062 if (TopTmp.isValid())
1063 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1064 else
1065 MostTopTmp = Tmp;
1066 TopTmp = Tmp;
1067 BaseTy = BaseTy->getPointeeType();
1068 }
1069 llvm::Type *Ty = BaseLVType;
1070 if (Tmp.isValid())
1071 Ty = Tmp.getElementType();
1072 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1073 if (Tmp.isValid()) {
1074 CGF.Builder.CreateStore(Addr, Tmp);
1075 return MostTopTmp;
1076 }
1077 return Address(Addr, BaseLVAlignment);
1078}
1079
1080Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1081 Address PrivateAddr) {
1082 const DeclRefExpr *DE;
1083 const VarDecl *OrigVD = nullptr;
1084 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1085 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1086 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1087 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1088 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1089 Base = TempASE->getBase()->IgnoreParenImpCasts();
1090 DE = cast<DeclRefExpr>(Base);
1091 OrigVD = cast<VarDecl>(DE->getDecl());
1092 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1093 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1094 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1095 Base = TempASE->getBase()->IgnoreParenImpCasts();
1096 DE = cast<DeclRefExpr>(Base);
1097 OrigVD = cast<VarDecl>(DE->getDecl());
1098 }
1099 if (OrigVD) {
1100 BaseDecls.emplace_back(OrigVD);
1101 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1102 LValue BaseLValue =
1103 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1104 OriginalBaseLValue);
1105 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1106 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1107 llvm::Value *Ptr =
1108 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1109 return castToBase(CGF, OrigVD->getType(),
1110 SharedAddresses[N].first.getType(),
1111 OriginalBaseLValue.getPointer()->getType(),
1112 OriginalBaseLValue.getAlignment(), Ptr);
1113 }
1114 BaseDecls.emplace_back(
1115 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1116 return PrivateAddr;
1117}
1118
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001119bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1120 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1121 return DRD && DRD->getInitializer();
1122}
1123
Alexey Bataev18095712014-10-10 12:19:54 +00001124LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001125 return CGF.EmitLoadOfPointerLValue(
1126 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1127 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001128}
1129
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001130void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001131 if (!CGF.HaveInsertPoint())
1132 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001133 // 1.2.2 OpenMP Language Terminology
1134 // Structured block - An executable statement with a single entry at the
1135 // top and a single exit at the bottom.
1136 // The point of exit cannot be a branch out of the structured block.
1137 // longjmp() and throw() must not violate the entry/exit criteria.
1138 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001139 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001140 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001141}
1142
Alexey Bataev62b63b12015-03-10 07:28:44 +00001143LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1144 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001145 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1146 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001147 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001148}
1149
Alexey Bataev9959db52014-05-06 10:08:46 +00001150CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001151 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001152 IdentTy = llvm::StructType::create(
1153 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1154 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001155 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001156 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001157
1158 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001159}
1160
Alexey Bataev91797552015-03-18 04:13:55 +00001161void CGOpenMPRuntime::clear() {
1162 InternalVars.clear();
1163}
1164
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001165static llvm::Function *
1166emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1167 const Expr *CombinerInitializer, const VarDecl *In,
1168 const VarDecl *Out, bool IsCombiner) {
1169 // void .omp_combiner.(Ty *in, Ty *out);
1170 auto &C = CGM.getContext();
1171 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1172 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001173 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001174 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001175 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001176 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001177 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001178 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001179 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001180 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001181 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1182 auto *Fn = llvm::Function::Create(
1183 FnTy, llvm::GlobalValue::InternalLinkage,
1184 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1185 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001186 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001187 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001188 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001189 CodeGenFunction CGF(CGM);
1190 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1191 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1192 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1193 CodeGenFunction::OMPPrivateScope Scope(CGF);
1194 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1195 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1196 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1197 .getAddress();
1198 });
1199 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1200 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1201 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1202 .getAddress();
1203 });
1204 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001205 if (!IsCombiner && Out->hasInit() &&
1206 !CGF.isTrivialInitializer(Out->getInit())) {
1207 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1208 Out->getType().getQualifiers(),
1209 /*IsInitializer=*/true);
1210 }
1211 if (CombinerInitializer)
1212 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001213 Scope.ForceCleanup();
1214 CGF.FinishFunction();
1215 return Fn;
1216}
1217
1218void CGOpenMPRuntime::emitUserDefinedReduction(
1219 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1220 if (UDRMap.count(D) > 0)
1221 return;
1222 auto &C = CGM.getContext();
1223 if (!In || !Out) {
1224 In = &C.Idents.get("omp_in");
1225 Out = &C.Idents.get("omp_out");
1226 }
1227 llvm::Function *Combiner = emitCombinerOrInitializer(
1228 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1229 cast<VarDecl>(D->lookup(Out).front()),
1230 /*IsCombiner=*/true);
1231 llvm::Function *Initializer = nullptr;
1232 if (auto *Init = D->getInitializer()) {
1233 if (!Priv || !Orig) {
1234 Priv = &C.Idents.get("omp_priv");
1235 Orig = &C.Idents.get("omp_orig");
1236 }
1237 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001238 CGM, D->getType(),
1239 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1240 : nullptr,
1241 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001242 cast<VarDecl>(D->lookup(Priv).front()),
1243 /*IsCombiner=*/false);
1244 }
1245 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1246 if (CGF) {
1247 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1248 Decls.second.push_back(D);
1249 }
1250}
1251
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001252std::pair<llvm::Function *, llvm::Function *>
1253CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1254 auto I = UDRMap.find(D);
1255 if (I != UDRMap.end())
1256 return I->second;
1257 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1258 return UDRMap.lookup(D);
1259}
1260
John McCall7f416cc2015-09-08 08:05:57 +00001261// Layout information for ident_t.
1262static CharUnits getIdentAlign(CodeGenModule &CGM) {
1263 return CGM.getPointerAlign();
1264}
1265static CharUnits getIdentSize(CodeGenModule &CGM) {
1266 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1267 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1268}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001269static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001270 // All the fields except the last are i32, so this works beautifully.
1271 return unsigned(Field) * CharUnits::fromQuantity(4);
1272}
1273static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001274 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001275 const llvm::Twine &Name = "") {
1276 auto Offset = getOffsetOfIdentField(Field);
1277 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1278}
1279
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001280static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1281 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1282 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1283 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001284 assert(ThreadIDVar->getType()->isPointerType() &&
1285 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001286 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001287 bool HasCancel = false;
1288 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1289 HasCancel = OPD->hasCancel();
1290 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1291 HasCancel = OPSD->hasCancel();
1292 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1293 HasCancel = OPFD->hasCancel();
1294 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001295 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001296 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001297 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001298}
1299
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001300llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1301 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1302 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1303 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1304 return emitParallelOrTeamsOutlinedFunction(
1305 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1306}
1307
1308llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1309 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1310 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1311 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1312 return emitParallelOrTeamsOutlinedFunction(
1313 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1314}
1315
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001316llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1317 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001318 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1319 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1320 bool Tied, unsigned &NumberOfParts) {
1321 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1322 PrePostActionTy &) {
1323 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1324 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1325 llvm::Value *TaskArgs[] = {
1326 UpLoc, ThreadID,
1327 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1328 TaskTVar->getType()->castAs<PointerType>())
1329 .getPointer()};
1330 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1331 };
1332 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1333 UntiedCodeGen);
1334 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001335 assert(!ThreadIDVar->getType()->isPointerType() &&
1336 "thread id variable must be of type kmp_int32 for tasks");
1337 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001338 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001339 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001340 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1341 InnermostKind,
1342 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001343 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001344 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1345 if (!Tied)
1346 NumberOfParts = Action.getNumberOfParts();
1347 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001348}
1349
Alexey Bataev50b3c952016-02-19 10:38:26 +00001350Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001351 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001352 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001353 if (!Entry) {
1354 if (!DefaultOpenMPPSource) {
1355 // Initialize default location for psource field of ident_t structure of
1356 // all ident_t objects. Format is ";file;function;line;column;;".
1357 // Taken from
1358 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1359 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001360 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001361 DefaultOpenMPPSource =
1362 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1363 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001364
John McCall23c9dc62016-11-28 22:18:27 +00001365 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001366 auto fields = builder.beginStruct(IdentTy);
1367 fields.addInt(CGM.Int32Ty, 0);
1368 fields.addInt(CGM.Int32Ty, Flags);
1369 fields.addInt(CGM.Int32Ty, 0);
1370 fields.addInt(CGM.Int32Ty, 0);
1371 fields.add(DefaultOpenMPPSource);
1372 auto DefaultOpenMPLocation =
1373 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1374 llvm::GlobalValue::PrivateLinkage);
1375 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1376
John McCall7f416cc2015-09-08 08:05:57 +00001377 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001378 }
John McCall7f416cc2015-09-08 08:05:57 +00001379 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001380}
1381
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001382llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1383 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001384 unsigned Flags) {
1385 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001386 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001387 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001388 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001389 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001390
1391 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1392
John McCall7f416cc2015-09-08 08:05:57 +00001393 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001394 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1395 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001396 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1397
Alexander Musmanc6388682014-12-15 07:07:06 +00001398 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1399 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001400 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001401 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001402 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1403 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001404 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001405 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001406 LocValue = AI;
1407
1408 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1409 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001410 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001411 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001412 }
1413
1414 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001415 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001416
Alexey Bataevf002aca2014-05-30 05:48:40 +00001417 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1418 if (OMPDebugLoc == nullptr) {
1419 SmallString<128> Buffer2;
1420 llvm::raw_svector_ostream OS2(Buffer2);
1421 // Build debug location
1422 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1423 OS2 << ";" << PLoc.getFilename() << ";";
1424 if (const FunctionDecl *FD =
1425 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1426 OS2 << FD->getQualifiedNameAsString();
1427 }
1428 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1429 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1430 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001431 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001432 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001433 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1434
John McCall7f416cc2015-09-08 08:05:57 +00001435 // Our callers always pass this to a runtime function, so for
1436 // convenience, go ahead and return a naked pointer.
1437 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001438}
1439
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001440llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1441 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001442 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1443
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001444 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001445 // Check whether we've already cached a load of the thread id in this
1446 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001447 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001448 if (I != OpenMPLocThreadIDMap.end()) {
1449 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001450 if (ThreadID != nullptr)
1451 return ThreadID;
1452 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001453 // If exceptions are enabled, do not use parameter to avoid possible crash.
1454 if (!CGF.getInvokeDest()) {
1455 if (auto *OMPRegionInfo =
1456 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1457 if (OMPRegionInfo->getThreadIDVariable()) {
1458 // Check if this an outlined function with thread id passed as argument.
1459 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1460 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1461 // If value loaded in entry block, cache it and use it everywhere in
1462 // function.
1463 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1464 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1465 Elem.second.ThreadID = ThreadID;
1466 }
1467 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001468 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001469 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001470 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001471
1472 // This is not an outlined function region - need to call __kmpc_int32
1473 // kmpc_global_thread_num(ident_t *loc).
1474 // Generate thread id value and cache this value for use across the
1475 // function.
1476 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1477 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1478 ThreadID =
1479 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1480 emitUpdateLocation(CGF, Loc));
1481 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1482 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001483 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001484}
1485
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001486void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001487 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001488 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1489 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001490 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1491 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1492 UDRMap.erase(D);
1493 }
1494 FunctionUDRMap.erase(CGF.CurFn);
1495 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001496}
1497
1498llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001499 if (!IdentTy) {
1500 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001501 return llvm::PointerType::getUnqual(IdentTy);
1502}
1503
1504llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001505 if (!Kmpc_MicroTy) {
1506 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1507 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1508 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1509 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1510 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001511 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1512}
1513
1514llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001515CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001516 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001517 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001518 case OMPRTL__kmpc_fork_call: {
1519 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1520 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001521 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1522 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001523 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001524 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001525 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1526 break;
1527 }
1528 case OMPRTL__kmpc_global_thread_num: {
1529 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001530 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001531 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001532 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001533 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1534 break;
1535 }
Alexey Bataev97720002014-11-11 04:05:39 +00001536 case OMPRTL__kmpc_threadprivate_cached: {
1537 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1538 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1539 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1540 CGM.VoidPtrTy, CGM.SizeTy,
1541 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1542 llvm::FunctionType *FnTy =
1543 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1544 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1545 break;
1546 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001547 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001548 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1549 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001550 llvm::Type *TypeParams[] = {
1551 getIdentTyPointerTy(), CGM.Int32Ty,
1552 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1553 llvm::FunctionType *FnTy =
1554 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1555 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1556 break;
1557 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001558 case OMPRTL__kmpc_critical_with_hint: {
1559 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1560 // kmp_critical_name *crit, uintptr_t hint);
1561 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1562 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1563 CGM.IntPtrTy};
1564 llvm::FunctionType *FnTy =
1565 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1566 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1567 break;
1568 }
Alexey Bataev97720002014-11-11 04:05:39 +00001569 case OMPRTL__kmpc_threadprivate_register: {
1570 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1571 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1572 // typedef void *(*kmpc_ctor)(void *);
1573 auto KmpcCtorTy =
1574 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1575 /*isVarArg*/ false)->getPointerTo();
1576 // typedef void *(*kmpc_cctor)(void *, void *);
1577 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1578 auto KmpcCopyCtorTy =
1579 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1580 /*isVarArg*/ false)->getPointerTo();
1581 // typedef void (*kmpc_dtor)(void *);
1582 auto KmpcDtorTy =
1583 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1584 ->getPointerTo();
1585 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1586 KmpcCopyCtorTy, KmpcDtorTy};
1587 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1588 /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1590 break;
1591 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001592 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001593 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1594 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001595 llvm::Type *TypeParams[] = {
1596 getIdentTyPointerTy(), CGM.Int32Ty,
1597 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1598 llvm::FunctionType *FnTy =
1599 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1600 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1601 break;
1602 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001603 case OMPRTL__kmpc_cancel_barrier: {
1604 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1605 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001606 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1607 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001608 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1609 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001610 break;
1611 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001612 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001613 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001614 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1615 llvm::FunctionType *FnTy =
1616 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1617 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1618 break;
1619 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001620 case OMPRTL__kmpc_for_static_fini: {
1621 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1622 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1623 llvm::FunctionType *FnTy =
1624 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1625 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1626 break;
1627 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001628 case OMPRTL__kmpc_push_num_threads: {
1629 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1630 // kmp_int32 num_threads)
1631 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1632 CGM.Int32Ty};
1633 llvm::FunctionType *FnTy =
1634 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1635 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1636 break;
1637 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001638 case OMPRTL__kmpc_serialized_parallel: {
1639 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1640 // global_tid);
1641 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1642 llvm::FunctionType *FnTy =
1643 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1644 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1645 break;
1646 }
1647 case OMPRTL__kmpc_end_serialized_parallel: {
1648 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1649 // global_tid);
1650 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1651 llvm::FunctionType *FnTy =
1652 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1653 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1654 break;
1655 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001656 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001657 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001658 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1659 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001660 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001661 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1662 break;
1663 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001664 case OMPRTL__kmpc_master: {
1665 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1666 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1667 llvm::FunctionType *FnTy =
1668 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1669 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1670 break;
1671 }
1672 case OMPRTL__kmpc_end_master: {
1673 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1674 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1675 llvm::FunctionType *FnTy =
1676 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1677 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1678 break;
1679 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001680 case OMPRTL__kmpc_omp_taskyield: {
1681 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1682 // int end_part);
1683 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1684 llvm::FunctionType *FnTy =
1685 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1686 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1687 break;
1688 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001689 case OMPRTL__kmpc_single: {
1690 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1691 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1692 llvm::FunctionType *FnTy =
1693 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1694 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1695 break;
1696 }
1697 case OMPRTL__kmpc_end_single: {
1698 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1700 llvm::FunctionType *FnTy =
1701 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1702 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1703 break;
1704 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001705 case OMPRTL__kmpc_omp_task_alloc: {
1706 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1707 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1708 // kmp_routine_entry_t *task_entry);
1709 assert(KmpRoutineEntryPtrTy != nullptr &&
1710 "Type kmp_routine_entry_t must be created.");
1711 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1712 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1713 // Return void * and then cast to particular kmp_task_t type.
1714 llvm::FunctionType *FnTy =
1715 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1716 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1717 break;
1718 }
1719 case OMPRTL__kmpc_omp_task: {
1720 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1721 // *new_task);
1722 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1723 CGM.VoidPtrTy};
1724 llvm::FunctionType *FnTy =
1725 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1726 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1727 break;
1728 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001729 case OMPRTL__kmpc_copyprivate: {
1730 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001731 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001732 // kmp_int32 didit);
1733 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1734 auto *CpyFnTy =
1735 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001736 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001737 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1738 CGM.Int32Ty};
1739 llvm::FunctionType *FnTy =
1740 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1741 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1742 break;
1743 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001744 case OMPRTL__kmpc_reduce: {
1745 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1746 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1747 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1748 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1749 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1750 /*isVarArg=*/false);
1751 llvm::Type *TypeParams[] = {
1752 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1753 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1754 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1755 llvm::FunctionType *FnTy =
1756 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1757 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1758 break;
1759 }
1760 case OMPRTL__kmpc_reduce_nowait: {
1761 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1762 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1763 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1764 // *lck);
1765 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1766 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1767 /*isVarArg=*/false);
1768 llvm::Type *TypeParams[] = {
1769 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1770 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1771 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1772 llvm::FunctionType *FnTy =
1773 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1775 break;
1776 }
1777 case OMPRTL__kmpc_end_reduce: {
1778 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1779 // kmp_critical_name *lck);
1780 llvm::Type *TypeParams[] = {
1781 getIdentTyPointerTy(), CGM.Int32Ty,
1782 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1783 llvm::FunctionType *FnTy =
1784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1786 break;
1787 }
1788 case OMPRTL__kmpc_end_reduce_nowait: {
1789 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1790 // kmp_critical_name *lck);
1791 llvm::Type *TypeParams[] = {
1792 getIdentTyPointerTy(), CGM.Int32Ty,
1793 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1794 llvm::FunctionType *FnTy =
1795 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1796 RTLFn =
1797 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1798 break;
1799 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001800 case OMPRTL__kmpc_omp_task_begin_if0: {
1801 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1802 // *new_task);
1803 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1804 CGM.VoidPtrTy};
1805 llvm::FunctionType *FnTy =
1806 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1807 RTLFn =
1808 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1809 break;
1810 }
1811 case OMPRTL__kmpc_omp_task_complete_if0: {
1812 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1813 // *new_task);
1814 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1815 CGM.VoidPtrTy};
1816 llvm::FunctionType *FnTy =
1817 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1818 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1819 /*Name=*/"__kmpc_omp_task_complete_if0");
1820 break;
1821 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001822 case OMPRTL__kmpc_ordered: {
1823 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1824 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1825 llvm::FunctionType *FnTy =
1826 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1827 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1828 break;
1829 }
1830 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001831 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001832 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1833 llvm::FunctionType *FnTy =
1834 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1835 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1836 break;
1837 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001838 case OMPRTL__kmpc_omp_taskwait: {
1839 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1840 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1841 llvm::FunctionType *FnTy =
1842 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1843 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1844 break;
1845 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001846 case OMPRTL__kmpc_taskgroup: {
1847 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1848 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1849 llvm::FunctionType *FnTy =
1850 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1851 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1852 break;
1853 }
1854 case OMPRTL__kmpc_end_taskgroup: {
1855 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1856 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1857 llvm::FunctionType *FnTy =
1858 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1859 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1860 break;
1861 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001862 case OMPRTL__kmpc_push_proc_bind: {
1863 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1864 // int proc_bind)
1865 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1866 llvm::FunctionType *FnTy =
1867 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1868 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1869 break;
1870 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001871 case OMPRTL__kmpc_omp_task_with_deps: {
1872 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1873 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1874 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1875 llvm::Type *TypeParams[] = {
1876 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1877 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1878 llvm::FunctionType *FnTy =
1879 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1880 RTLFn =
1881 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1882 break;
1883 }
1884 case OMPRTL__kmpc_omp_wait_deps: {
1885 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1886 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1887 // kmp_depend_info_t *noalias_dep_list);
1888 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1889 CGM.Int32Ty, CGM.VoidPtrTy,
1890 CGM.Int32Ty, CGM.VoidPtrTy};
1891 llvm::FunctionType *FnTy =
1892 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1894 break;
1895 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001896 case OMPRTL__kmpc_cancellationpoint: {
1897 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1898 // global_tid, kmp_int32 cncl_kind)
1899 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1900 llvm::FunctionType *FnTy =
1901 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1902 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1903 break;
1904 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001905 case OMPRTL__kmpc_cancel: {
1906 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1907 // kmp_int32 cncl_kind)
1908 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1909 llvm::FunctionType *FnTy =
1910 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1911 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1912 break;
1913 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001914 case OMPRTL__kmpc_push_num_teams: {
1915 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1916 // kmp_int32 num_teams, kmp_int32 num_threads)
1917 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1918 CGM.Int32Ty};
1919 llvm::FunctionType *FnTy =
1920 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1921 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1922 break;
1923 }
1924 case OMPRTL__kmpc_fork_teams: {
1925 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1926 // microtask, ...);
1927 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1928 getKmpc_MicroPointerTy()};
1929 llvm::FunctionType *FnTy =
1930 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1931 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1932 break;
1933 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001934 case OMPRTL__kmpc_taskloop: {
1935 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1936 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1937 // sched, kmp_uint64 grainsize, void *task_dup);
1938 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1939 CGM.IntTy,
1940 CGM.VoidPtrTy,
1941 CGM.IntTy,
1942 CGM.Int64Ty->getPointerTo(),
1943 CGM.Int64Ty->getPointerTo(),
1944 CGM.Int64Ty,
1945 CGM.IntTy,
1946 CGM.IntTy,
1947 CGM.Int64Ty,
1948 CGM.VoidPtrTy};
1949 llvm::FunctionType *FnTy =
1950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1952 break;
1953 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001954 case OMPRTL__kmpc_doacross_init: {
1955 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1956 // num_dims, struct kmp_dim *dims);
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1958 CGM.Int32Ty,
1959 CGM.Int32Ty,
1960 CGM.VoidPtrTy};
1961 llvm::FunctionType *FnTy =
1962 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1963 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1964 break;
1965 }
1966 case OMPRTL__kmpc_doacross_fini: {
1967 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1968 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1969 llvm::FunctionType *FnTy =
1970 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1971 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1972 break;
1973 }
1974 case OMPRTL__kmpc_doacross_post: {
1975 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1976 // *vec);
1977 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1978 CGM.Int64Ty->getPointerTo()};
1979 llvm::FunctionType *FnTy =
1980 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1981 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1982 break;
1983 }
1984 case OMPRTL__kmpc_doacross_wait: {
1985 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1986 // *vec);
1987 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1988 CGM.Int64Ty->getPointerTo()};
1989 llvm::FunctionType *FnTy =
1990 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1991 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1992 break;
1993 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001994 case OMPRTL__kmpc_task_reduction_init: {
1995 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1996 // *data);
1997 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1998 llvm::FunctionType *FnTy =
1999 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2000 RTLFn =
2001 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2002 break;
2003 }
2004 case OMPRTL__kmpc_task_reduction_get_th_data: {
2005 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2006 // *d);
2007 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2008 llvm::FunctionType *FnTy =
2009 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2010 RTLFn = CGM.CreateRuntimeFunction(
2011 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2012 break;
2013 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002014 case OMPRTL__tgt_target: {
2015 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2016 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2017 // *arg_types);
2018 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2019 CGM.VoidPtrTy,
2020 CGM.Int32Ty,
2021 CGM.VoidPtrPtrTy,
2022 CGM.VoidPtrPtrTy,
2023 CGM.SizeTy->getPointerTo(),
2024 CGM.Int32Ty->getPointerTo()};
2025 llvm::FunctionType *FnTy =
2026 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2027 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2028 break;
2029 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002030 case OMPRTL__tgt_target_teams: {
2031 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2032 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2033 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2034 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2035 CGM.VoidPtrTy,
2036 CGM.Int32Ty,
2037 CGM.VoidPtrPtrTy,
2038 CGM.VoidPtrPtrTy,
2039 CGM.SizeTy->getPointerTo(),
2040 CGM.Int32Ty->getPointerTo(),
2041 CGM.Int32Ty,
2042 CGM.Int32Ty};
2043 llvm::FunctionType *FnTy =
2044 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2045 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2046 break;
2047 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002048 case OMPRTL__tgt_register_lib: {
2049 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2050 QualType ParamTy =
2051 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2052 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2053 llvm::FunctionType *FnTy =
2054 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2055 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2056 break;
2057 }
2058 case OMPRTL__tgt_unregister_lib: {
2059 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2060 QualType ParamTy =
2061 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2062 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2063 llvm::FunctionType *FnTy =
2064 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2065 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2066 break;
2067 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002068 case OMPRTL__tgt_target_data_begin: {
2069 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2070 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2071 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2072 CGM.Int32Ty,
2073 CGM.VoidPtrPtrTy,
2074 CGM.VoidPtrPtrTy,
2075 CGM.SizeTy->getPointerTo(),
2076 CGM.Int32Ty->getPointerTo()};
2077 llvm::FunctionType *FnTy =
2078 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2079 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2080 break;
2081 }
2082 case OMPRTL__tgt_target_data_end: {
2083 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2084 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2085 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2086 CGM.Int32Ty,
2087 CGM.VoidPtrPtrTy,
2088 CGM.VoidPtrPtrTy,
2089 CGM.SizeTy->getPointerTo(),
2090 CGM.Int32Ty->getPointerTo()};
2091 llvm::FunctionType *FnTy =
2092 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2093 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2094 break;
2095 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002096 case OMPRTL__tgt_target_data_update: {
2097 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2098 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2099 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2100 CGM.Int32Ty,
2101 CGM.VoidPtrPtrTy,
2102 CGM.VoidPtrPtrTy,
2103 CGM.SizeTy->getPointerTo(),
2104 CGM.Int32Ty->getPointerTo()};
2105 llvm::FunctionType *FnTy =
2106 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2107 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2108 break;
2109 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002110 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002111 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002112 return RTLFn;
2113}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002114
Alexander Musman21212e42015-03-13 10:38:23 +00002115llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2116 bool IVSigned) {
2117 assert((IVSize == 32 || IVSize == 64) &&
2118 "IV size is not compatible with the omp runtime");
2119 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2120 : "__kmpc_for_static_init_4u")
2121 : (IVSigned ? "__kmpc_for_static_init_8"
2122 : "__kmpc_for_static_init_8u");
2123 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2124 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2125 llvm::Type *TypeParams[] = {
2126 getIdentTyPointerTy(), // loc
2127 CGM.Int32Ty, // tid
2128 CGM.Int32Ty, // schedtype
2129 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2130 PtrTy, // p_lower
2131 PtrTy, // p_upper
2132 PtrTy, // p_stride
2133 ITy, // incr
2134 ITy // chunk
2135 };
2136 llvm::FunctionType *FnTy =
2137 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2138 return CGM.CreateRuntimeFunction(FnTy, Name);
2139}
2140
Alexander Musman92bdaab2015-03-12 13:37:50 +00002141llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2142 bool IVSigned) {
2143 assert((IVSize == 32 || IVSize == 64) &&
2144 "IV size is not compatible with the omp runtime");
2145 auto Name =
2146 IVSize == 32
2147 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2148 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2149 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2150 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2151 CGM.Int32Ty, // tid
2152 CGM.Int32Ty, // schedtype
2153 ITy, // lower
2154 ITy, // upper
2155 ITy, // stride
2156 ITy // chunk
2157 };
2158 llvm::FunctionType *FnTy =
2159 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2160 return CGM.CreateRuntimeFunction(FnTy, Name);
2161}
2162
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002163llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2164 bool IVSigned) {
2165 assert((IVSize == 32 || IVSize == 64) &&
2166 "IV size is not compatible with the omp runtime");
2167 auto Name =
2168 IVSize == 32
2169 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2170 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2171 llvm::Type *TypeParams[] = {
2172 getIdentTyPointerTy(), // loc
2173 CGM.Int32Ty, // tid
2174 };
2175 llvm::FunctionType *FnTy =
2176 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2177 return CGM.CreateRuntimeFunction(FnTy, Name);
2178}
2179
Alexander Musman92bdaab2015-03-12 13:37:50 +00002180llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2181 bool IVSigned) {
2182 assert((IVSize == 32 || IVSize == 64) &&
2183 "IV size is not compatible with the omp runtime");
2184 auto Name =
2185 IVSize == 32
2186 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2187 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2188 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2189 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2190 llvm::Type *TypeParams[] = {
2191 getIdentTyPointerTy(), // loc
2192 CGM.Int32Ty, // tid
2193 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2194 PtrTy, // p_lower
2195 PtrTy, // p_upper
2196 PtrTy // p_stride
2197 };
2198 llvm::FunctionType *FnTy =
2199 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2200 return CGM.CreateRuntimeFunction(FnTy, Name);
2201}
2202
Alexey Bataev97720002014-11-11 04:05:39 +00002203llvm::Constant *
2204CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002205 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2206 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002207 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002208 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002209 Twine(CGM.getMangledName(VD)) + ".cache.");
2210}
2211
John McCall7f416cc2015-09-08 08:05:57 +00002212Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2213 const VarDecl *VD,
2214 Address VDAddr,
2215 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002216 if (CGM.getLangOpts().OpenMPUseTLS &&
2217 CGM.getContext().getTargetInfo().isTLSSupported())
2218 return VDAddr;
2219
John McCall7f416cc2015-09-08 08:05:57 +00002220 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002221 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002222 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2223 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002224 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2225 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002226 return Address(CGF.EmitRuntimeCall(
2227 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2228 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002229}
2230
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002231void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002232 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002233 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2234 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2235 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002236 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2237 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002238 OMPLoc);
2239 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2240 // to register constructor/destructor for variable.
2241 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002242 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2243 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002244 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002245 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002246 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002247}
2248
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002249llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002250 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002251 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002252 if (CGM.getLangOpts().OpenMPUseTLS &&
2253 CGM.getContext().getTargetInfo().isTLSSupported())
2254 return nullptr;
2255
Alexey Bataev97720002014-11-11 04:05:39 +00002256 VD = VD->getDefinition(CGM.getContext());
2257 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2258 ThreadPrivateWithDefinition.insert(VD);
2259 QualType ASTTy = VD->getType();
2260
2261 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2262 auto Init = VD->getAnyInitializer();
2263 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2264 // Generate function that re-emits the declaration's initializer into the
2265 // threadprivate copy of the variable VD
2266 CodeGenFunction CtorCGF(CGM);
2267 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002268 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2269 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002270 Args.push_back(&Dst);
2271
John McCallc56a8b32016-03-11 04:30:31 +00002272 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2273 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002274 auto FTy = CGM.getTypes().GetFunctionType(FI);
2275 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002276 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002277 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2278 Args, SourceLocation());
2279 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002280 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002281 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002282 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2283 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2284 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002285 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2286 /*IsInitializer=*/true);
2287 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002288 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002289 CGM.getContext().VoidPtrTy, Dst.getLocation());
2290 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2291 CtorCGF.FinishFunction();
2292 Ctor = Fn;
2293 }
2294 if (VD->getType().isDestructedType() != QualType::DK_none) {
2295 // Generate function that emits destructor call for the threadprivate copy
2296 // of the variable VD
2297 CodeGenFunction DtorCGF(CGM);
2298 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002299 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2300 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002301 Args.push_back(&Dst);
2302
John McCallc56a8b32016-03-11 04:30:31 +00002303 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2304 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002305 auto FTy = CGM.getTypes().GetFunctionType(FI);
2306 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002307 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002308 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002309 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2310 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002311 // Create a scope with an artificial location for the body of this function.
2312 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002313 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2314 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002315 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2316 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002317 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2318 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2319 DtorCGF.FinishFunction();
2320 Dtor = Fn;
2321 }
2322 // Do not emit init function if it is not required.
2323 if (!Ctor && !Dtor)
2324 return nullptr;
2325
2326 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2327 auto CopyCtorTy =
2328 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2329 /*isVarArg=*/false)->getPointerTo();
2330 // Copying constructor for the threadprivate variable.
2331 // Must be NULL - reserved by runtime, but currently it requires that this
2332 // parameter is always NULL. Otherwise it fires assertion.
2333 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2334 if (Ctor == nullptr) {
2335 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2336 /*isVarArg=*/false)->getPointerTo();
2337 Ctor = llvm::Constant::getNullValue(CtorTy);
2338 }
2339 if (Dtor == nullptr) {
2340 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2341 /*isVarArg=*/false)->getPointerTo();
2342 Dtor = llvm::Constant::getNullValue(DtorTy);
2343 }
2344 if (!CGF) {
2345 auto InitFunctionTy =
2346 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2347 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002348 InitFunctionTy, ".__omp_threadprivate_init_.",
2349 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002350 CodeGenFunction InitCGF(CGM);
2351 FunctionArgList ArgList;
2352 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2353 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2354 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002355 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002356 InitCGF.FinishFunction();
2357 return InitFunction;
2358 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002359 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002360 }
2361 return nullptr;
2362}
2363
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002364Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2365 QualType VarType,
2366 StringRef Name) {
2367 llvm::Twine VarName(Name, ".artificial.");
2368 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2369 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2370 llvm::Value *Args[] = {
2371 emitUpdateLocation(CGF, SourceLocation()),
2372 getThreadID(CGF, SourceLocation()),
2373 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2374 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2375 /*IsSigned=*/false),
2376 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2377 return Address(
2378 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2379 CGF.EmitRuntimeCall(
2380 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2381 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2382 CGM.getPointerAlign());
2383}
2384
Alexey Bataev1d677132015-04-22 13:57:31 +00002385/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2386/// function. Here is the logic:
2387/// if (Cond) {
2388/// ThenGen();
2389/// } else {
2390/// ElseGen();
2391/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002392void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2393 const RegionCodeGenTy &ThenGen,
2394 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002395 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2396
2397 // If the condition constant folds and can be elided, try to avoid emitting
2398 // the condition and the dead arm of the if/else.
2399 bool CondConstant;
2400 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002401 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002402 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002403 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002404 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002405 return;
2406 }
2407
2408 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2409 // emit the conditional branch.
2410 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2411 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2412 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2413 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2414
2415 // Emit the 'then' code.
2416 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002417 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002418 CGF.EmitBranch(ContBlock);
2419 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002420 // There is no need to emit line number for unconditional branch.
2421 (void)ApplyDebugLocation::CreateEmpty(CGF);
2422 CGF.EmitBlock(ElseBlock);
2423 ElseGen(CGF);
2424 // There is no need to emit line number for unconditional branch.
2425 (void)ApplyDebugLocation::CreateEmpty(CGF);
2426 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002427 // Emit the continuation block for code after the if.
2428 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002429}
2430
Alexey Bataev1d677132015-04-22 13:57:31 +00002431void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2432 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002433 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002434 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002435 if (!CGF.HaveInsertPoint())
2436 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002437 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002438 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2439 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002440 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002441 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002442 llvm::Value *Args[] = {
2443 RTLoc,
2444 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002445 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002446 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2447 RealArgs.append(std::begin(Args), std::end(Args));
2448 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2449
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002450 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002451 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2452 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002453 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2454 PrePostActionTy &) {
2455 auto &RT = CGF.CGM.getOpenMPRuntime();
2456 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002457 // Build calls:
2458 // __kmpc_serialized_parallel(&Loc, GTid);
2459 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002460 CGF.EmitRuntimeCall(
2461 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002462
Alexey Bataev1d677132015-04-22 13:57:31 +00002463 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002464 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002465 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002466 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2467 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002468 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002469 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2470 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2471 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2472 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002473 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002474
Alexey Bataev1d677132015-04-22 13:57:31 +00002475 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002476 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002477 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002478 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2479 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002480 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002481 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002482 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002483 else {
2484 RegionCodeGenTy ThenRCG(ThenGen);
2485 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002486 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002487}
2488
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002489// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002490// thread-ID variable (it is passed in a first argument of the outlined function
2491// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2492// regular serial code region, get thread ID by calling kmp_int32
2493// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2494// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002495Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2496 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002497 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002498 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002499 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002500 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002501
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002502 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002503 auto Int32Ty =
2504 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2505 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2506 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002507 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002508
2509 return ThreadIDTemp;
2510}
2511
Alexey Bataev97720002014-11-11 04:05:39 +00002512llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002513CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002514 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002515 SmallString<256> Buffer;
2516 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002517 Out << Name;
2518 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002519 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2520 if (Elem.second) {
2521 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002522 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002523 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002524 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002525
David Blaikie13156b62014-11-19 03:06:06 +00002526 return Elem.second = new llvm::GlobalVariable(
2527 CGM.getModule(), Ty, /*IsConstant*/ false,
2528 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2529 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002530}
2531
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002532llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002533 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002534 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002535}
2536
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002537namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002538/// Common pre(post)-action for different OpenMP constructs.
2539class CommonActionTy final : public PrePostActionTy {
2540 llvm::Value *EnterCallee;
2541 ArrayRef<llvm::Value *> EnterArgs;
2542 llvm::Value *ExitCallee;
2543 ArrayRef<llvm::Value *> ExitArgs;
2544 bool Conditional;
2545 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002546
2547public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002548 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2549 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2550 bool Conditional = false)
2551 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2552 ExitArgs(ExitArgs), Conditional(Conditional) {}
2553 void Enter(CodeGenFunction &CGF) override {
2554 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2555 if (Conditional) {
2556 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2557 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2558 ContBlock = CGF.createBasicBlock("omp_if.end");
2559 // Generate the branch (If-stmt)
2560 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2561 CGF.EmitBlock(ThenBlock);
2562 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002563 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002564 void Done(CodeGenFunction &CGF) {
2565 // Emit the rest of blocks/branches
2566 CGF.EmitBranch(ContBlock);
2567 CGF.EmitBlock(ContBlock, true);
2568 }
2569 void Exit(CodeGenFunction &CGF) override {
2570 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002571 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002572};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002573} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002574
2575void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2576 StringRef CriticalName,
2577 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002578 SourceLocation Loc, const Expr *Hint) {
2579 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002580 // CriticalOpGen();
2581 // __kmpc_end_critical(ident_t *, gtid, Lock);
2582 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002583 if (!CGF.HaveInsertPoint())
2584 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002585 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2586 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002587 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2588 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002589 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002590 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2591 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2592 }
2593 CommonActionTy Action(
2594 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2595 : OMPRTL__kmpc_critical),
2596 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2597 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002598 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002599}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002600
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002601void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002602 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002603 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002604 if (!CGF.HaveInsertPoint())
2605 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002606 // if(__kmpc_master(ident_t *, gtid)) {
2607 // MasterOpGen();
2608 // __kmpc_end_master(ident_t *, gtid);
2609 // }
2610 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002611 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002612 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2613 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2614 /*Conditional=*/true);
2615 MasterOpGen.setAction(Action);
2616 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2617 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002618}
2619
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002620void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2621 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002622 if (!CGF.HaveInsertPoint())
2623 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002624 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2625 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002626 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002627 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002628 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002629 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2630 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002631}
2632
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002633void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2634 const RegionCodeGenTy &TaskgroupOpGen,
2635 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002636 if (!CGF.HaveInsertPoint())
2637 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002638 // __kmpc_taskgroup(ident_t *, gtid);
2639 // TaskgroupOpGen();
2640 // __kmpc_end_taskgroup(ident_t *, gtid);
2641 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002642 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2643 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2644 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2645 Args);
2646 TaskgroupOpGen.setAction(Action);
2647 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002648}
2649
John McCall7f416cc2015-09-08 08:05:57 +00002650/// Given an array of pointers to variables, project the address of a
2651/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002652static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2653 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002654 // Pull out the pointer to the variable.
2655 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002656 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002657 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2658
2659 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002660 Addr = CGF.Builder.CreateElementBitCast(
2661 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002662 return Addr;
2663}
2664
Alexey Bataeva63048e2015-03-23 06:18:07 +00002665static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002666 CodeGenModule &CGM, llvm::Type *ArgsType,
2667 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2668 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002669 auto &C = CGM.getContext();
2670 // void copy_func(void *LHSArg, void *RHSArg);
2671 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002672 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2673 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002674 Args.push_back(&LHSArg);
2675 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002676 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002677 auto *Fn = llvm::Function::Create(
2678 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2679 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002680 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002681 CodeGenFunction CGF(CGM);
2682 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002683 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002684 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002685 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2686 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2687 ArgsType), CGF.getPointerAlign());
2688 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2689 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2690 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002691 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2692 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2693 // ...
2694 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002695 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002696 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2697 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2698
2699 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2700 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2701
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002702 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2703 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002704 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002705 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002706 CGF.FinishFunction();
2707 return Fn;
2708}
2709
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002710void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002711 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002712 SourceLocation Loc,
2713 ArrayRef<const Expr *> CopyprivateVars,
2714 ArrayRef<const Expr *> SrcExprs,
2715 ArrayRef<const Expr *> DstExprs,
2716 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002717 if (!CGF.HaveInsertPoint())
2718 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002719 assert(CopyprivateVars.size() == SrcExprs.size() &&
2720 CopyprivateVars.size() == DstExprs.size() &&
2721 CopyprivateVars.size() == AssignmentOps.size());
2722 auto &C = CGM.getContext();
2723 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002724 // if(__kmpc_single(ident_t *, gtid)) {
2725 // SingleOpGen();
2726 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002727 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002728 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002729 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2730 // <copy_func>, did_it);
2731
John McCall7f416cc2015-09-08 08:05:57 +00002732 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002733 if (!CopyprivateVars.empty()) {
2734 // int32 did_it = 0;
2735 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2736 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002737 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002738 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002739 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002740 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002741 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2742 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2743 /*Conditional=*/true);
2744 SingleOpGen.setAction(Action);
2745 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2746 if (DidIt.isValid()) {
2747 // did_it = 1;
2748 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2749 }
2750 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002751 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2752 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002753 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002754 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2755 auto CopyprivateArrayTy =
2756 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2757 /*IndexTypeQuals=*/0);
2758 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002759 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002760 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2761 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002762 Address Elem = CGF.Builder.CreateConstArrayGEP(
2763 CopyprivateList, I, CGF.getPointerSize());
2764 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002765 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002766 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2767 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002768 }
2769 // Build function that copies private values from single region to all other
2770 // threads in the corresponding parallel region.
2771 auto *CpyFn = emitCopyprivateCopyFunction(
2772 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002773 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002774 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002775 Address CL =
2776 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2777 CGF.VoidPtrTy);
2778 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002779 llvm::Value *Args[] = {
2780 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2781 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002782 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002783 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002784 CpyFn, // void (*) (void *, void *) <copy_func>
2785 DidItVal // i32 did_it
2786 };
2787 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2788 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002789}
2790
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002791void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2792 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002793 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002794 if (!CGF.HaveInsertPoint())
2795 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002796 // __kmpc_ordered(ident_t *, gtid);
2797 // OrderedOpGen();
2798 // __kmpc_end_ordered(ident_t *, gtid);
2799 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002800 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002801 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002802 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2803 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2804 Args);
2805 OrderedOpGen.setAction(Action);
2806 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2807 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002808 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002809 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002810}
2811
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002812void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002813 OpenMPDirectiveKind Kind, bool EmitChecks,
2814 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002815 if (!CGF.HaveInsertPoint())
2816 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002817 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002818 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002819 unsigned Flags;
2820 if (Kind == OMPD_for)
2821 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2822 else if (Kind == OMPD_sections)
2823 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2824 else if (Kind == OMPD_single)
2825 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2826 else if (Kind == OMPD_barrier)
2827 Flags = OMP_IDENT_BARRIER_EXPL;
2828 else
2829 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002830 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2831 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002832 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2833 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002834 if (auto *OMPRegionInfo =
2835 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002836 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002837 auto *Result = CGF.EmitRuntimeCall(
2838 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002839 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002840 // if (__kmpc_cancel_barrier()) {
2841 // exit from construct;
2842 // }
2843 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2844 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2845 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2846 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2847 CGF.EmitBlock(ExitBB);
2848 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002849 auto CancelDestination =
2850 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002851 CGF.EmitBranchThroughCleanup(CancelDestination);
2852 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2853 }
2854 return;
2855 }
2856 }
2857 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002858}
2859
Alexander Musmanc6388682014-12-15 07:07:06 +00002860/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2861static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002862 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002863 switch (ScheduleKind) {
2864 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002865 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2866 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002867 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002868 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002869 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002870 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002871 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002872 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2873 case OMPC_SCHEDULE_auto:
2874 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002875 case OMPC_SCHEDULE_unknown:
2876 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002877 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002878 }
2879 llvm_unreachable("Unexpected runtime schedule");
2880}
2881
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002882/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2883static OpenMPSchedType
2884getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2885 // only static is allowed for dist_schedule
2886 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2887}
2888
Alexander Musmanc6388682014-12-15 07:07:06 +00002889bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2890 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002891 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002892 return Schedule == OMP_sch_static;
2893}
2894
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002895bool CGOpenMPRuntime::isStaticNonchunked(
2896 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2897 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2898 return Schedule == OMP_dist_sch_static;
2899}
2900
2901
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002902bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002903 auto Schedule =
2904 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002905 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2906 return Schedule != OMP_sch_static;
2907}
2908
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002909static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2910 OpenMPScheduleClauseModifier M1,
2911 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002912 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002913 switch (M1) {
2914 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002915 Modifier = OMP_sch_modifier_monotonic;
2916 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002917 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002918 Modifier = OMP_sch_modifier_nonmonotonic;
2919 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002920 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002921 if (Schedule == OMP_sch_static_chunked)
2922 Schedule = OMP_sch_static_balanced_chunked;
2923 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002924 case OMPC_SCHEDULE_MODIFIER_last:
2925 case OMPC_SCHEDULE_MODIFIER_unknown:
2926 break;
2927 }
2928 switch (M2) {
2929 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002930 Modifier = OMP_sch_modifier_monotonic;
2931 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002932 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002933 Modifier = OMP_sch_modifier_nonmonotonic;
2934 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002935 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002936 if (Schedule == OMP_sch_static_chunked)
2937 Schedule = OMP_sch_static_balanced_chunked;
2938 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002939 case OMPC_SCHEDULE_MODIFIER_last:
2940 case OMPC_SCHEDULE_MODIFIER_unknown:
2941 break;
2942 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002943 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002944}
2945
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002946void CGOpenMPRuntime::emitForDispatchInit(
2947 CodeGenFunction &CGF, SourceLocation Loc,
2948 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2949 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002950 if (!CGF.HaveInsertPoint())
2951 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002952 OpenMPSchedType Schedule = getRuntimeSchedule(
2953 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002954 assert(Ordered ||
2955 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002956 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2957 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002958 // Call __kmpc_dispatch_init(
2959 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2960 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2961 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002962
John McCall7f416cc2015-09-08 08:05:57 +00002963 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002964 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2965 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002966 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002967 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2968 CGF.Builder.getInt32(addMonoNonMonoModifier(
2969 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002970 DispatchValues.LB, // Lower
2971 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002972 CGF.Builder.getIntN(IVSize, 1), // Stride
2973 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002974 };
2975 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2976}
2977
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002978static void emitForStaticInitCall(
2979 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2980 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2981 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002982 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002983 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002984 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002985
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002986 assert(!Values.Ordered);
2987 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2988 Schedule == OMP_sch_static_balanced_chunked ||
2989 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2990 Schedule == OMP_dist_sch_static ||
2991 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002992
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002993 // Call __kmpc_for_static_init(
2994 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2995 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2996 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2997 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2998 llvm::Value *Chunk = Values.Chunk;
2999 if (Chunk == nullptr) {
3000 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3001 Schedule == OMP_dist_sch_static) &&
3002 "expected static non-chunked schedule");
3003 // If the Chunk was not specified in the clause - use default value 1.
3004 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3005 } else {
3006 assert((Schedule == OMP_sch_static_chunked ||
3007 Schedule == OMP_sch_static_balanced_chunked ||
3008 Schedule == OMP_ord_static_chunked ||
3009 Schedule == OMP_dist_sch_static_chunked) &&
3010 "expected static chunked schedule");
3011 }
3012 llvm::Value *Args[] = {
3013 UpdateLocation,
3014 ThreadId,
3015 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3016 M2)), // Schedule type
3017 Values.IL.getPointer(), // &isLastIter
3018 Values.LB.getPointer(), // &LB
3019 Values.UB.getPointer(), // &UB
3020 Values.ST.getPointer(), // &Stride
3021 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3022 Chunk // Chunk
3023 };
3024 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003025}
3026
John McCall7f416cc2015-09-08 08:05:57 +00003027void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3028 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003029 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003030 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003031 const StaticRTInput &Values) {
3032 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3033 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3034 assert(isOpenMPWorksharingDirective(DKind) &&
3035 "Expected loop-based or sections-based directive.");
3036 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3037 isOpenMPLoopDirective(DKind)
3038 ? OMP_IDENT_WORK_LOOP
3039 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003040 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003041 auto *StaticInitFunction =
3042 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003043 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003044 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003045}
John McCall7f416cc2015-09-08 08:05:57 +00003046
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003047void CGOpenMPRuntime::emitDistributeStaticInit(
3048 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003049 OpenMPDistScheduleClauseKind SchedKind,
3050 const CGOpenMPRuntime::StaticRTInput &Values) {
3051 OpenMPSchedType ScheduleNum =
3052 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3053 auto *UpdatedLocation =
3054 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003055 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003056 auto *StaticInitFunction =
3057 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003058 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3059 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003060 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003061}
3062
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003063void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003064 SourceLocation Loc,
3065 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003066 if (!CGF.HaveInsertPoint())
3067 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003068 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003069 llvm::Value *Args[] = {
3070 emitUpdateLocation(CGF, Loc,
3071 isOpenMPDistributeDirective(DKind)
3072 ? OMP_IDENT_WORK_DISTRIBUTE
3073 : isOpenMPLoopDirective(DKind)
3074 ? OMP_IDENT_WORK_LOOP
3075 : OMP_IDENT_WORK_SECTIONS),
3076 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003077 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3078 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003079}
3080
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003081void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3082 SourceLocation Loc,
3083 unsigned IVSize,
3084 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003085 if (!CGF.HaveInsertPoint())
3086 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003087 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003088 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003089 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3090}
3091
Alexander Musman92bdaab2015-03-12 13:37:50 +00003092llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3093 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003094 bool IVSigned, Address IL,
3095 Address LB, Address UB,
3096 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003097 // Call __kmpc_dispatch_next(
3098 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3099 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3100 // kmp_int[32|64] *p_stride);
3101 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003102 emitUpdateLocation(CGF, Loc),
3103 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003104 IL.getPointer(), // &isLastIter
3105 LB.getPointer(), // &Lower
3106 UB.getPointer(), // &Upper
3107 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003108 };
3109 llvm::Value *Call =
3110 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3111 return CGF.EmitScalarConversion(
3112 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003113 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003114}
3115
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003116void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3117 llvm::Value *NumThreads,
3118 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003119 if (!CGF.HaveInsertPoint())
3120 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003121 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3122 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003123 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003124 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003125 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3126 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003127}
3128
Alexey Bataev7f210c62015-06-18 13:40:03 +00003129void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3130 OpenMPProcBindClauseKind ProcBind,
3131 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003132 if (!CGF.HaveInsertPoint())
3133 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003134 // Constants for proc bind value accepted by the runtime.
3135 enum ProcBindTy {
3136 ProcBindFalse = 0,
3137 ProcBindTrue,
3138 ProcBindMaster,
3139 ProcBindClose,
3140 ProcBindSpread,
3141 ProcBindIntel,
3142 ProcBindDefault
3143 } RuntimeProcBind;
3144 switch (ProcBind) {
3145 case OMPC_PROC_BIND_master:
3146 RuntimeProcBind = ProcBindMaster;
3147 break;
3148 case OMPC_PROC_BIND_close:
3149 RuntimeProcBind = ProcBindClose;
3150 break;
3151 case OMPC_PROC_BIND_spread:
3152 RuntimeProcBind = ProcBindSpread;
3153 break;
3154 case OMPC_PROC_BIND_unknown:
3155 llvm_unreachable("Unsupported proc_bind value.");
3156 }
3157 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3158 llvm::Value *Args[] = {
3159 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3160 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3161 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3162}
3163
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003164void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3165 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003166 if (!CGF.HaveInsertPoint())
3167 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003168 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003169 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3170 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003171}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003172
Alexey Bataev62b63b12015-03-10 07:28:44 +00003173namespace {
3174/// \brief Indexes of fields for type kmp_task_t.
3175enum KmpTaskTFields {
3176 /// \brief List of shared variables.
3177 KmpTaskTShareds,
3178 /// \brief Task routine.
3179 KmpTaskTRoutine,
3180 /// \brief Partition id for the untied tasks.
3181 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003182 /// Function with call of destructors for private variables.
3183 Data1,
3184 /// Task priority.
3185 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003186 /// (Taskloops only) Lower bound.
3187 KmpTaskTLowerBound,
3188 /// (Taskloops only) Upper bound.
3189 KmpTaskTUpperBound,
3190 /// (Taskloops only) Stride.
3191 KmpTaskTStride,
3192 /// (Taskloops only) Is last iteration flag.
3193 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003194 /// (Taskloops only) Reduction data.
3195 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003196};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003197} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003198
Samuel Antaoee8fb302016-01-06 13:42:12 +00003199bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3200 // FIXME: Add other entries type when they become supported.
3201 return OffloadEntriesTargetRegion.empty();
3202}
3203
3204/// \brief Initialize target region entry.
3205void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3206 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3207 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003208 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003209 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3210 "only required for the device "
3211 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003212 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003213 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3214 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003215 ++OffloadingEntriesNum;
3216}
3217
3218void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3219 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3220 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003221 llvm::Constant *Addr, llvm::Constant *ID,
3222 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003223 // If we are emitting code for a target, the entry is already initialized,
3224 // only has to be registered.
3225 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003226 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003227 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003228 auto &Entry =
3229 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003230 assert(Entry.isValid() && "Entry not initialized!");
3231 Entry.setAddress(Addr);
3232 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003233 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003234 return;
3235 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003236 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003237 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003238 }
3239}
3240
3241bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003242 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3243 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003244 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3245 if (PerDevice == OffloadEntriesTargetRegion.end())
3246 return false;
3247 auto PerFile = PerDevice->second.find(FileID);
3248 if (PerFile == PerDevice->second.end())
3249 return false;
3250 auto PerParentName = PerFile->second.find(ParentName);
3251 if (PerParentName == PerFile->second.end())
3252 return false;
3253 auto PerLine = PerParentName->second.find(LineNum);
3254 if (PerLine == PerParentName->second.end())
3255 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003256 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003257 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003258 return false;
3259 return true;
3260}
3261
3262void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3263 const OffloadTargetRegionEntryInfoActTy &Action) {
3264 // Scan all target region entries and perform the provided action.
3265 for (auto &D : OffloadEntriesTargetRegion)
3266 for (auto &F : D.second)
3267 for (auto &P : F.second)
3268 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003269 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003270}
3271
3272/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3273/// \a Codegen. This is used to emit the two functions that register and
3274/// unregister the descriptor of the current compilation unit.
3275static llvm::Function *
3276createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3277 const RegionCodeGenTy &Codegen) {
3278 auto &C = CGM.getContext();
3279 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003280 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003281 Args.push_back(&DummyPtr);
3282
3283 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003284 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003285 auto FTy = CGM.getTypes().GetFunctionType(FI);
3286 auto *Fn =
3287 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3288 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3289 Codegen(CGF);
3290 CGF.FinishFunction();
3291 return Fn;
3292}
3293
3294llvm::Function *
3295CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3296
3297 // If we don't have entries or if we are emitting code for the device, we
3298 // don't need to do anything.
3299 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3300 return nullptr;
3301
3302 auto &M = CGM.getModule();
3303 auto &C = CGM.getContext();
3304
3305 // Get list of devices we care about
3306 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3307
3308 // We should be creating an offloading descriptor only if there are devices
3309 // specified.
3310 assert(!Devices.empty() && "No OpenMP offloading devices??");
3311
3312 // Create the external variables that will point to the begin and end of the
3313 // host entries section. These will be defined by the linker.
3314 auto *OffloadEntryTy =
3315 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3316 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3317 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003318 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003319 ".omp_offloading.entries_begin");
3320 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3321 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003322 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003323 ".omp_offloading.entries_end");
3324
3325 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003326 auto *DeviceImageTy = cast<llvm::StructType>(
3327 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003328 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003329 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003330
3331 for (unsigned i = 0; i < Devices.size(); ++i) {
3332 StringRef T = Devices[i].getTriple();
3333 auto *ImgBegin = new llvm::GlobalVariable(
3334 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003335 /*Initializer=*/nullptr,
3336 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003337 auto *ImgEnd = new llvm::GlobalVariable(
3338 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003339 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003340
John McCall6c9f1fdb2016-11-19 08:17:24 +00003341 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3342 Dev.add(ImgBegin);
3343 Dev.add(ImgEnd);
3344 Dev.add(HostEntriesBegin);
3345 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003346 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003347 }
3348
3349 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003350 llvm::GlobalVariable *DeviceImages =
3351 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3352 CGM.getPointerAlign(),
3353 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003354 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003355
3356 // This is a Zero array to be used in the creation of the constant expressions
3357 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3358 llvm::Constant::getNullValue(CGM.Int32Ty)};
3359
3360 // Create the target region descriptor.
3361 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3362 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003363 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003364 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3365 DescInit.addInt(CGM.Int32Ty, Devices.size());
3366 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3367 DeviceImages,
3368 Index));
3369 DescInit.add(HostEntriesBegin);
3370 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003371
John McCall6c9f1fdb2016-11-19 08:17:24 +00003372 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3373 CGM.getPointerAlign(),
3374 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003375
3376 // Emit code to register or unregister the descriptor at execution
3377 // startup or closing, respectively.
3378
3379 // Create a variable to drive the registration and unregistration of the
3380 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3381 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3382 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003383 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003384
3385 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003386 CGM, ".omp_offloading.descriptor_unreg",
3387 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003388 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3389 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003390 });
3391 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003392 CGM, ".omp_offloading.descriptor_reg",
3393 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003394 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3395 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003396 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3397 });
George Rokos29d0f002017-05-27 03:03:13 +00003398 if (CGM.supportsCOMDAT()) {
3399 // It is sufficient to call registration function only once, so create a
3400 // COMDAT group for registration/unregistration functions and associated
3401 // data. That would reduce startup time and code size. Registration
3402 // function serves as a COMDAT group key.
3403 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3404 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3405 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3406 RegFn->setComdat(ComdatKey);
3407 UnRegFn->setComdat(ComdatKey);
3408 DeviceImages->setComdat(ComdatKey);
3409 Desc->setComdat(ComdatKey);
3410 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003411 return RegFn;
3412}
3413
Samuel Antao2de62b02016-02-13 23:35:10 +00003414void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003415 llvm::Constant *Addr, uint64_t Size,
3416 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003417 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003418 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3419 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3420 llvm::LLVMContext &C = CGM.getModule().getContext();
3421 llvm::Module &M = CGM.getModule();
3422
3423 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003424 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003425
3426 // Create constant string with the name.
3427 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3428
3429 llvm::GlobalVariable *Str =
3430 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3431 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3432 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003433 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003434 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3435
John McCall6c9f1fdb2016-11-19 08:17:24 +00003436 // We can't have any padding between symbols, so we need to have 1-byte
3437 // alignment.
3438 auto Align = CharUnits::fromQuantity(1);
3439
Samuel Antaoee8fb302016-01-06 13:42:12 +00003440 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003441 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003442 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3443 EntryInit.add(AddrPtr);
3444 EntryInit.add(StrPtr);
3445 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003446 EntryInit.addInt(CGM.Int32Ty, Flags);
3447 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003448 llvm::GlobalVariable *Entry =
3449 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3450 Align,
3451 /*constant*/ true,
3452 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003453
3454 // The entry has to be created in the section the linker expects it to be.
3455 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003456}
3457
3458void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3459 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003460 // can easily figure out what to emit. The produced metadata looks like
3461 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003462 //
3463 // !omp_offload.info = !{!1, ...}
3464 //
3465 // Right now we only generate metadata for function that contain target
3466 // regions.
3467
3468 // If we do not have entries, we dont need to do anything.
3469 if (OffloadEntriesInfoManager.empty())
3470 return;
3471
3472 llvm::Module &M = CGM.getModule();
3473 llvm::LLVMContext &C = M.getContext();
3474 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3475 OrderedEntries(OffloadEntriesInfoManager.size());
3476
3477 // Create the offloading info metadata node.
3478 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3479
Simon Pilgrim2c518802017-03-30 14:13:19 +00003480 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003481 auto getMDInt = [&](unsigned v) {
3482 return llvm::ConstantAsMetadata::get(
3483 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3484 };
3485
3486 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3487
3488 // Create function that emits metadata for each target region entry;
3489 auto &&TargetRegionMetadataEmitter = [&](
3490 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003491 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3492 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3493 // Generate metadata for target regions. Each entry of this metadata
3494 // contains:
3495 // - Entry 0 -> Kind of this type of metadata (0).
3496 // - Entry 1 -> Device ID of the file where the entry was identified.
3497 // - Entry 2 -> File ID of the file where the entry was identified.
3498 // - Entry 3 -> Mangled name of the function where the entry was identified.
3499 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003500 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003501 // The first element of the metadata node is the kind.
3502 Ops.push_back(getMDInt(E.getKind()));
3503 Ops.push_back(getMDInt(DeviceID));
3504 Ops.push_back(getMDInt(FileID));
3505 Ops.push_back(getMDString(ParentName));
3506 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003507 Ops.push_back(getMDInt(E.getOrder()));
3508
3509 // Save this entry in the right position of the ordered entries array.
3510 OrderedEntries[E.getOrder()] = &E;
3511
3512 // Add metadata to the named metadata node.
3513 MD->addOperand(llvm::MDNode::get(C, Ops));
3514 };
3515
3516 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3517 TargetRegionMetadataEmitter);
3518
3519 for (auto *E : OrderedEntries) {
3520 assert(E && "All ordered entries must exist!");
3521 if (auto *CE =
3522 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3523 E)) {
3524 assert(CE->getID() && CE->getAddress() &&
3525 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003526 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003527 } else
3528 llvm_unreachable("Unsupported entry kind.");
3529 }
3530}
3531
3532/// \brief Loads all the offload entries information from the host IR
3533/// metadata.
3534void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3535 // If we are in target mode, load the metadata from the host IR. This code has
3536 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3537
3538 if (!CGM.getLangOpts().OpenMPIsDevice)
3539 return;
3540
3541 if (CGM.getLangOpts().OMPHostIRFile.empty())
3542 return;
3543
3544 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3545 if (Buf.getError())
3546 return;
3547
3548 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003549 auto ME = expectedToErrorOrAndEmitErrors(
3550 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003551
3552 if (ME.getError())
3553 return;
3554
3555 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3556 if (!MD)
3557 return;
3558
3559 for (auto I : MD->operands()) {
3560 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3561
3562 auto getMDInt = [&](unsigned Idx) {
3563 llvm::ConstantAsMetadata *V =
3564 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3565 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3566 };
3567
3568 auto getMDString = [&](unsigned Idx) {
3569 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3570 return V->getString();
3571 };
3572
3573 switch (getMDInt(0)) {
3574 default:
3575 llvm_unreachable("Unexpected metadata!");
3576 break;
3577 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3578 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3579 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3580 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3581 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003582 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003583 break;
3584 }
3585 }
3586}
3587
Alexey Bataev62b63b12015-03-10 07:28:44 +00003588void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3589 if (!KmpRoutineEntryPtrTy) {
3590 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3591 auto &C = CGM.getContext();
3592 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3593 FunctionProtoType::ExtProtoInfo EPI;
3594 KmpRoutineEntryPtrQTy = C.getPointerType(
3595 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3596 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3597 }
3598}
3599
Alexey Bataevc71a4092015-09-11 10:29:41 +00003600static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3601 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003602 auto *Field = FieldDecl::Create(
3603 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3604 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3605 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3606 Field->setAccess(AS_public);
3607 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003608 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003609}
3610
Samuel Antaoee8fb302016-01-06 13:42:12 +00003611QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3612
3613 // Make sure the type of the entry is already created. This is the type we
3614 // have to create:
3615 // struct __tgt_offload_entry{
3616 // void *addr; // Pointer to the offload entry info.
3617 // // (function or global)
3618 // char *name; // Name of the function or global.
3619 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003620 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3621 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003622 // };
3623 if (TgtOffloadEntryQTy.isNull()) {
3624 ASTContext &C = CGM.getContext();
3625 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3626 RD->startDefinition();
3627 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3628 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3629 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003630 addFieldToRecordDecl(
3631 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3632 addFieldToRecordDecl(
3633 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003634 RD->completeDefinition();
3635 TgtOffloadEntryQTy = C.getRecordType(RD);
3636 }
3637 return TgtOffloadEntryQTy;
3638}
3639
3640QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3641 // These are the types we need to build:
3642 // struct __tgt_device_image{
3643 // void *ImageStart; // Pointer to the target code start.
3644 // void *ImageEnd; // Pointer to the target code end.
3645 // // We also add the host entries to the device image, as it may be useful
3646 // // for the target runtime to have access to that information.
3647 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3648 // // the entries.
3649 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3650 // // entries (non inclusive).
3651 // };
3652 if (TgtDeviceImageQTy.isNull()) {
3653 ASTContext &C = CGM.getContext();
3654 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3655 RD->startDefinition();
3656 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3657 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3658 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3659 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3660 RD->completeDefinition();
3661 TgtDeviceImageQTy = C.getRecordType(RD);
3662 }
3663 return TgtDeviceImageQTy;
3664}
3665
3666QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3667 // struct __tgt_bin_desc{
3668 // int32_t NumDevices; // Number of devices supported.
3669 // __tgt_device_image *DeviceImages; // Arrays of device images
3670 // // (one per device).
3671 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3672 // // entries.
3673 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3674 // // entries (non inclusive).
3675 // };
3676 if (TgtBinaryDescriptorQTy.isNull()) {
3677 ASTContext &C = CGM.getContext();
3678 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3679 RD->startDefinition();
3680 addFieldToRecordDecl(
3681 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3682 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3683 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3684 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3685 RD->completeDefinition();
3686 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3687 }
3688 return TgtBinaryDescriptorQTy;
3689}
3690
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003691namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003692struct PrivateHelpersTy {
3693 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3694 const VarDecl *PrivateElemInit)
3695 : Original(Original), PrivateCopy(PrivateCopy),
3696 PrivateElemInit(PrivateElemInit) {}
3697 const VarDecl *Original;
3698 const VarDecl *PrivateCopy;
3699 const VarDecl *PrivateElemInit;
3700};
3701typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003702} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003703
Alexey Bataev9e034042015-05-05 04:05:12 +00003704static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003705createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003706 if (!Privates.empty()) {
3707 auto &C = CGM.getContext();
3708 // Build struct .kmp_privates_t. {
3709 // /* private vars */
3710 // };
3711 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3712 RD->startDefinition();
3713 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003714 auto *VD = Pair.second.Original;
3715 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003716 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003717 auto *FD = addFieldToRecordDecl(C, RD, Type);
3718 if (VD->hasAttrs()) {
3719 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3720 E(VD->getAttrs().end());
3721 I != E; ++I)
3722 FD->addAttr(*I);
3723 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003724 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003725 RD->completeDefinition();
3726 return RD;
3727 }
3728 return nullptr;
3729}
3730
Alexey Bataev9e034042015-05-05 04:05:12 +00003731static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003732createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3733 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003734 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003735 auto &C = CGM.getContext();
3736 // Build struct kmp_task_t {
3737 // void * shareds;
3738 // kmp_routine_entry_t routine;
3739 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003740 // kmp_cmplrdata_t data1;
3741 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003742 // For taskloops additional fields:
3743 // kmp_uint64 lb;
3744 // kmp_uint64 ub;
3745 // kmp_int64 st;
3746 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003747 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003748 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003749 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3750 UD->startDefinition();
3751 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3752 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3753 UD->completeDefinition();
3754 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003755 auto *RD = C.buildImplicitRecord("kmp_task_t");
3756 RD->startDefinition();
3757 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3758 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3759 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003760 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3761 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003762 if (isOpenMPTaskLoopDirective(Kind)) {
3763 QualType KmpUInt64Ty =
3764 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3765 QualType KmpInt64Ty =
3766 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3767 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3768 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3769 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3770 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003771 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003772 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003773 RD->completeDefinition();
3774 return RD;
3775}
3776
3777static RecordDecl *
3778createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003779 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003780 auto &C = CGM.getContext();
3781 // Build struct kmp_task_t_with_privates {
3782 // kmp_task_t task_data;
3783 // .kmp_privates_t. privates;
3784 // };
3785 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3786 RD->startDefinition();
3787 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003788 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3789 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3790 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003791 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003792 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003793}
3794
3795/// \brief Emit a proxy function which accepts kmp_task_t as the second
3796/// argument.
3797/// \code
3798/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003799/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003800/// For taskloops:
3801/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003802/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003803/// return 0;
3804/// }
3805/// \endcode
3806static llvm::Value *
3807emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003808 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3809 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003810 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003811 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3812 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003813 auto &C = CGM.getContext();
3814 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003815 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3816 ImplicitParamDecl::Other);
3817 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3818 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3819 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003820 Args.push_back(&GtidArg);
3821 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003822 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003823 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003824 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3825 auto *TaskEntry =
3826 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3827 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003828 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003829 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003830 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3831
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003832 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003833 // tt,
3834 // For taskloops:
3835 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3836 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003837 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003838 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003839 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3840 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3841 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003842 auto *KmpTaskTWithPrivatesQTyRD =
3843 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003844 LValue Base =
3845 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003846 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3847 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3848 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003849 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003850
3851 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3852 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003853 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003854 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003855 CGF.ConvertTypeForMem(SharedsPtrTy));
3856
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003857 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3858 llvm::Value *PrivatesParam;
3859 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3860 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3861 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003862 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003863 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003864 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003865
Alexey Bataev7292c292016-04-25 12:22:29 +00003866 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3867 TaskPrivatesMap,
3868 CGF.Builder
3869 .CreatePointerBitCastOrAddrSpaceCast(
3870 TDBase.getAddress(), CGF.VoidPtrTy)
3871 .getPointer()};
3872 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3873 std::end(CommonArgs));
3874 if (isOpenMPTaskLoopDirective(Kind)) {
3875 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3876 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3877 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3878 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3879 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3880 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3881 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3882 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3883 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3884 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3885 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3886 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003887 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3888 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3889 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003890 CallArgs.push_back(LBParam);
3891 CallArgs.push_back(UBParam);
3892 CallArgs.push_back(StParam);
3893 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003894 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003895 }
3896 CallArgs.push_back(SharedsParam);
3897
Alexey Bataev3c595a62017-08-14 15:01:03 +00003898 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3899 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003900 CGF.EmitStoreThroughLValue(
3901 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003902 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003903 CGF.FinishFunction();
3904 return TaskEntry;
3905}
3906
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003907static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3908 SourceLocation Loc,
3909 QualType KmpInt32Ty,
3910 QualType KmpTaskTWithPrivatesPtrQTy,
3911 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003912 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003913 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003914 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3915 ImplicitParamDecl::Other);
3916 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3917 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3918 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003919 Args.push_back(&GtidArg);
3920 Args.push_back(&TaskTypeArg);
3921 FunctionType::ExtInfo Info;
3922 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003923 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003924 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3925 auto *DestructorFn =
3926 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3927 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003928 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3929 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003930 CodeGenFunction CGF(CGM);
3931 CGF.disableDebugInfo();
3932 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3933 Args);
3934
Alexey Bataev31300ed2016-02-04 11:27:03 +00003935 LValue Base = CGF.EmitLoadOfPointerLValue(
3936 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3937 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003938 auto *KmpTaskTWithPrivatesQTyRD =
3939 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3940 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003941 Base = CGF.EmitLValueForField(Base, *FI);
3942 for (auto *Field :
3943 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3944 if (auto DtorKind = Field->getType().isDestructedType()) {
3945 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3946 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3947 }
3948 }
3949 CGF.FinishFunction();
3950 return DestructorFn;
3951}
3952
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003953/// \brief Emit a privates mapping function for correct handling of private and
3954/// firstprivate variables.
3955/// \code
3956/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3957/// **noalias priv1,..., <tyn> **noalias privn) {
3958/// *priv1 = &.privates.priv1;
3959/// ...;
3960/// *privn = &.privates.privn;
3961/// }
3962/// \endcode
3963static llvm::Value *
3964emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003965 ArrayRef<const Expr *> PrivateVars,
3966 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003967 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003968 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003969 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003970 auto &C = CGM.getContext();
3971 FunctionArgList Args;
3972 ImplicitParamDecl TaskPrivatesArg(
3973 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003974 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3975 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003976 Args.push_back(&TaskPrivatesArg);
3977 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3978 unsigned Counter = 1;
3979 for (auto *E: PrivateVars) {
3980 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003981 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3982 C.getPointerType(C.getPointerType(E->getType()))
3983 .withConst()
3984 .withRestrict(),
3985 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003986 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3987 PrivateVarsPos[VD] = Counter;
3988 ++Counter;
3989 }
3990 for (auto *E : FirstprivateVars) {
3991 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003992 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3993 C.getPointerType(C.getPointerType(E->getType()))
3994 .withConst()
3995 .withRestrict(),
3996 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003997 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3998 PrivateVarsPos[VD] = Counter;
3999 ++Counter;
4000 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004001 for (auto *E: LastprivateVars) {
4002 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004003 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4004 C.getPointerType(C.getPointerType(E->getType()))
4005 .withConst()
4006 .withRestrict(),
4007 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004008 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4009 PrivateVarsPos[VD] = Counter;
4010 ++Counter;
4011 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004012 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004013 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004014 auto *TaskPrivatesMapTy =
4015 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4016 auto *TaskPrivatesMap = llvm::Function::Create(
4017 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4018 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004019 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4020 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004021 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004022 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004023 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004024 CodeGenFunction CGF(CGM);
4025 CGF.disableDebugInfo();
4026 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4027 TaskPrivatesMapFnInfo, Args);
4028
4029 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004030 LValue Base = CGF.EmitLoadOfPointerLValue(
4031 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4032 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004033 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4034 Counter = 0;
4035 for (auto *Field : PrivatesQTyRD->fields()) {
4036 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4037 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004038 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004039 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4040 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004041 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004042 ++Counter;
4043 }
4044 CGF.FinishFunction();
4045 return TaskPrivatesMap;
4046}
4047
Alexey Bataev9e034042015-05-05 04:05:12 +00004048static int array_pod_sort_comparator(const PrivateDataTy *P1,
4049 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004050 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4051}
4052
Alexey Bataevf93095a2016-05-05 08:46:22 +00004053/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004054static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004055 const OMPExecutableDirective &D,
4056 Address KmpTaskSharedsPtr, LValue TDBase,
4057 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4058 QualType SharedsTy, QualType SharedsPtrTy,
4059 const OMPTaskDataTy &Data,
4060 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4061 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004062 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4063 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4064 LValue SrcBase;
4065 if (!Data.FirstprivateVars.empty()) {
4066 SrcBase = CGF.MakeAddrLValue(
4067 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4068 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4069 SharedsTy);
4070 }
4071 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4072 cast<CapturedStmt>(*D.getAssociatedStmt()));
4073 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4074 for (auto &&Pair : Privates) {
4075 auto *VD = Pair.second.PrivateCopy;
4076 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004077 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4078 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004079 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004080 if (auto *Elem = Pair.second.PrivateElemInit) {
4081 auto *OriginalVD = Pair.second.Original;
4082 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4083 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4084 SharedRefLValue = CGF.MakeAddrLValue(
4085 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004086 SharedRefLValue.getType(),
4087 LValueBaseInfo(AlignmentSource::Decl,
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004088 SharedRefLValue.getBaseInfo().getMayAlias()),
4089 CGF.CGM.getTBAAAccessInfo(SharedRefLValue.getType()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004090 QualType Type = OriginalVD->getType();
4091 if (Type->isArrayType()) {
4092 // Initialize firstprivate array.
4093 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4094 // Perform simple memcpy.
4095 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4096 SharedRefLValue.getAddress(), Type);
4097 } else {
4098 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004099 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004100 CGF.EmitOMPAggregateAssign(
4101 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4102 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4103 Address SrcElement) {
4104 // Clean up any temporaries needed by the initialization.
4105 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4106 InitScope.addPrivate(
4107 Elem, [SrcElement]() -> Address { return SrcElement; });
4108 (void)InitScope.Privatize();
4109 // Emit initialization for single element.
4110 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4111 CGF, &CapturesInfo);
4112 CGF.EmitAnyExprToMem(Init, DestElement,
4113 Init->getType().getQualifiers(),
4114 /*IsInitializer=*/false);
4115 });
4116 }
4117 } else {
4118 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4119 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4120 return SharedRefLValue.getAddress();
4121 });
4122 (void)InitScope.Privatize();
4123 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4124 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4125 /*capturedByInit=*/false);
4126 }
4127 } else
4128 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4129 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004130 ++FI;
4131 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004132}
4133
4134/// Check if duplication function is required for taskloops.
4135static bool checkInitIsRequired(CodeGenFunction &CGF,
4136 ArrayRef<PrivateDataTy> Privates) {
4137 bool InitRequired = false;
4138 for (auto &&Pair : Privates) {
4139 auto *VD = Pair.second.PrivateCopy;
4140 auto *Init = VD->getAnyInitializer();
4141 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4142 !CGF.isTrivialInitializer(Init));
4143 }
4144 return InitRequired;
4145}
4146
4147
4148/// Emit task_dup function (for initialization of
4149/// private/firstprivate/lastprivate vars and last_iter flag)
4150/// \code
4151/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4152/// lastpriv) {
4153/// // setup lastprivate flag
4154/// task_dst->last = lastpriv;
4155/// // could be constructor calls here...
4156/// }
4157/// \endcode
4158static llvm::Value *
4159emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4160 const OMPExecutableDirective &D,
4161 QualType KmpTaskTWithPrivatesPtrQTy,
4162 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4163 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4164 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4165 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4166 auto &C = CGM.getContext();
4167 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004168 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4169 KmpTaskTWithPrivatesPtrQTy,
4170 ImplicitParamDecl::Other);
4171 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4172 KmpTaskTWithPrivatesPtrQTy,
4173 ImplicitParamDecl::Other);
4174 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4175 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004176 Args.push_back(&DstArg);
4177 Args.push_back(&SrcArg);
4178 Args.push_back(&LastprivArg);
4179 auto &TaskDupFnInfo =
4180 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4181 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4182 auto *TaskDup =
4183 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4184 ".omp_task_dup.", &CGM.getModule());
4185 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4186 CodeGenFunction CGF(CGM);
4187 CGF.disableDebugInfo();
4188 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4189
4190 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4191 CGF.GetAddrOfLocalVar(&DstArg),
4192 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4193 // task_dst->liter = lastpriv;
4194 if (WithLastIter) {
4195 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4196 LValue Base = CGF.EmitLValueForField(
4197 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4198 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4199 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4200 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4201 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4202 }
4203
4204 // Emit initial values for private copies (if any).
4205 assert(!Privates.empty());
4206 Address KmpTaskSharedsPtr = Address::invalid();
4207 if (!Data.FirstprivateVars.empty()) {
4208 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4209 CGF.GetAddrOfLocalVar(&SrcArg),
4210 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4211 LValue Base = CGF.EmitLValueForField(
4212 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4213 KmpTaskSharedsPtr = Address(
4214 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4215 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4216 KmpTaskTShareds)),
4217 Loc),
4218 CGF.getNaturalTypeAlignment(SharedsTy));
4219 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004220 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4221 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004222 CGF.FinishFunction();
4223 return TaskDup;
4224}
4225
Alexey Bataev8a831592016-05-10 10:36:51 +00004226/// Checks if destructor function is required to be generated.
4227/// \return true if cleanups are required, false otherwise.
4228static bool
4229checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4230 bool NeedsCleanup = false;
4231 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4232 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4233 for (auto *FD : PrivateRD->fields()) {
4234 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4235 if (NeedsCleanup)
4236 break;
4237 }
4238 return NeedsCleanup;
4239}
4240
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004241CGOpenMPRuntime::TaskResultTy
4242CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4243 const OMPExecutableDirective &D,
4244 llvm::Value *TaskFunction, QualType SharedsTy,
4245 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004246 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004247 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004248 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004249 auto I = Data.PrivateCopies.begin();
4250 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004251 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4252 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004253 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004254 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4255 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004256 ++I;
4257 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004258 I = Data.FirstprivateCopies.begin();
4259 auto IElemInitRef = Data.FirstprivateInits.begin();
4260 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004261 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4262 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004263 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004264 PrivateHelpersTy(
4265 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4266 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004267 ++I;
4268 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004269 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004270 I = Data.LastprivateCopies.begin();
4271 for (auto *E : Data.LastprivateVars) {
4272 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4273 Privates.push_back(std::make_pair(
4274 C.getDeclAlign(VD),
4275 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4276 /*PrivateElemInit=*/nullptr)));
4277 ++I;
4278 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004279 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4280 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004281 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4282 // Build type kmp_routine_entry_t (if not built yet).
4283 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004284 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004285 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4286 if (SavedKmpTaskloopTQTy.isNull()) {
4287 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4288 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4289 }
4290 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004291 } else {
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004292 assert(D.getDirectiveKind() == OMPD_task &&
4293 "Expected taskloop or task directive");
4294 if (SavedKmpTaskTQTy.isNull()) {
4295 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4296 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4297 }
4298 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004299 }
4300 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004301 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004302 auto *KmpTaskTWithPrivatesQTyRD =
4303 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4304 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4305 QualType KmpTaskTWithPrivatesPtrQTy =
4306 C.getPointerType(KmpTaskTWithPrivatesQTy);
4307 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4308 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004309 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004310 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4311
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004312 // Emit initial values for private copies (if any).
4313 llvm::Value *TaskPrivatesMap = nullptr;
4314 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004315 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004316 if (!Privates.empty()) {
4317 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004318 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4319 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4320 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004321 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4322 TaskPrivatesMap, TaskPrivatesMapTy);
4323 } else {
4324 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4325 cast<llvm::PointerType>(TaskPrivatesMapTy));
4326 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004327 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4328 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004329 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004330 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4331 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4332 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004333
4334 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4335 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4336 // kmp_routine_entry_t *task_entry);
4337 // Task flags. Format is taken from
4338 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4339 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004340 enum {
4341 TiedFlag = 0x1,
4342 FinalFlag = 0x2,
4343 DestructorsFlag = 0x8,
4344 PriorityFlag = 0x20
4345 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004346 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004347 bool NeedsCleanup = false;
4348 if (!Privates.empty()) {
4349 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4350 if (NeedsCleanup)
4351 Flags = Flags | DestructorsFlag;
4352 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004353 if (Data.Priority.getInt())
4354 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004355 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004356 Data.Final.getPointer()
4357 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004358 CGF.Builder.getInt32(FinalFlag),
4359 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004360 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004361 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004362 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004363 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4364 getThreadID(CGF, Loc), TaskFlags,
4365 KmpTaskTWithPrivatesTySize, SharedsSize,
4366 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4367 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004368 auto *NewTask = CGF.EmitRuntimeCall(
4369 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004370 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4371 NewTask, KmpTaskTWithPrivatesPtrTy);
4372 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4373 KmpTaskTWithPrivatesQTy);
4374 LValue TDBase =
4375 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004376 // Fill the data in the resulting kmp_task_t record.
4377 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004378 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004379 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004380 KmpTaskSharedsPtr =
4381 Address(CGF.EmitLoadOfScalar(
4382 CGF.EmitLValueForField(
4383 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4384 KmpTaskTShareds)),
4385 Loc),
4386 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004387 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004388 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004389 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004390 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004391 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004392 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4393 SharedsTy, SharedsPtrTy, Data, Privates,
4394 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004395 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4396 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4397 Result.TaskDupFn = emitTaskDupFunction(
4398 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4399 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4400 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004401 }
4402 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004403 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4404 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004405 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004406 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4407 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4408 if (NeedsCleanup) {
4409 llvm::Value *DestructorFn = emitDestructorsFunction(
4410 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4411 KmpTaskTWithPrivatesQTy);
4412 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4413 LValue DestructorsLV = CGF.EmitLValueForField(
4414 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4415 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4416 DestructorFn, KmpRoutineEntryPtrTy),
4417 DestructorsLV);
4418 }
4419 // Set priority.
4420 if (Data.Priority.getInt()) {
4421 LValue Data2LV = CGF.EmitLValueForField(
4422 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4423 LValue PriorityLV = CGF.EmitLValueForField(
4424 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4425 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4426 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004427 Result.NewTask = NewTask;
4428 Result.TaskEntry = TaskEntry;
4429 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4430 Result.TDBase = TDBase;
4431 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4432 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004433}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004434
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004435void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4436 const OMPExecutableDirective &D,
4437 llvm::Value *TaskFunction,
4438 QualType SharedsTy, Address Shareds,
4439 const Expr *IfCond,
4440 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004441 if (!CGF.HaveInsertPoint())
4442 return;
4443
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004444 TaskResultTy Result =
4445 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4446 llvm::Value *NewTask = Result.NewTask;
4447 llvm::Value *TaskEntry = Result.TaskEntry;
4448 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4449 LValue TDBase = Result.TDBase;
4450 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004451 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004452 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004453 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004454 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004455 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004456 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004457 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004458 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4459 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004460 QualType FlagsTy =
4461 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004462 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4463 if (KmpDependInfoTy.isNull()) {
4464 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4465 KmpDependInfoRD->startDefinition();
4466 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4467 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4468 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4469 KmpDependInfoRD->completeDefinition();
4470 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004471 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004472 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004473 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004474 // Define type kmp_depend_info[<Dependences.size()>];
4475 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004476 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004477 ArrayType::Normal, /*IndexTypeQuals=*/0);
4478 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004479 DependenciesArray =
4480 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004481 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004482 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004483 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004484 llvm::Value *Size;
4485 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004486 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4487 LValue UpAddrLVal =
4488 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4489 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004490 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004491 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004492 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004493 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4494 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004495 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004496 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004497 auto Base = CGF.MakeAddrLValue(
4498 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004499 KmpDependInfoTy);
4500 // deps[i].base_addr = &<Dependences[i].second>;
4501 auto BaseAddrLVal = CGF.EmitLValueForField(
4502 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004503 CGF.EmitStoreOfScalar(
4504 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4505 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004506 // deps[i].len = sizeof(<Dependences[i].second>);
4507 auto LenLVal = CGF.EmitLValueForField(
4508 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4509 CGF.EmitStoreOfScalar(Size, LenLVal);
4510 // deps[i].flags = <Dependences[i].first>;
4511 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004512 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004513 case OMPC_DEPEND_in:
4514 DepKind = DepIn;
4515 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004516 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004517 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004518 case OMPC_DEPEND_inout:
4519 DepKind = DepInOut;
4520 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004521 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004522 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004523 case OMPC_DEPEND_unknown:
4524 llvm_unreachable("Unknown task dependence type");
4525 }
4526 auto FlagsLVal = CGF.EmitLValueForField(
4527 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4528 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4529 FlagsLVal);
4530 }
John McCall7f416cc2015-09-08 08:05:57 +00004531 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4532 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004533 CGF.VoidPtrTy);
4534 }
4535
Alexey Bataev62b63b12015-03-10 07:28:44 +00004536 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4537 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004538 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4539 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4540 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4541 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004542 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004543 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004544 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4545 llvm::Value *DepTaskArgs[7];
4546 if (NumDependencies) {
4547 DepTaskArgs[0] = UpLoc;
4548 DepTaskArgs[1] = ThreadID;
4549 DepTaskArgs[2] = NewTask;
4550 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4551 DepTaskArgs[4] = DependenciesArray.getPointer();
4552 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4553 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4554 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004555 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4556 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004557 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004558 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004559 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4560 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4561 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4562 }
John McCall7f416cc2015-09-08 08:05:57 +00004563 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004564 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004565 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004566 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004567 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004568 TaskArgs);
4569 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004570 // Check if parent region is untied and build return for untied task;
4571 if (auto *Region =
4572 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4573 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004574 };
John McCall7f416cc2015-09-08 08:05:57 +00004575
4576 llvm::Value *DepWaitTaskArgs[6];
4577 if (NumDependencies) {
4578 DepWaitTaskArgs[0] = UpLoc;
4579 DepWaitTaskArgs[1] = ThreadID;
4580 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4581 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4582 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4583 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4584 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004585 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004586 NumDependencies, &DepWaitTaskArgs,
4587 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004588 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004589 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4590 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4591 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4592 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4593 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004594 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004595 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004596 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004597 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004598 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4599 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004600 Action.Enter(CGF);
4601 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004602 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004603 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004604 };
4605
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004606 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4607 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004608 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4609 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004610 RegionCodeGenTy RCG(CodeGen);
4611 CommonActionTy Action(
4612 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4613 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4614 RCG.setAction(Action);
4615 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004616 };
John McCall7f416cc2015-09-08 08:05:57 +00004617
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004618 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004619 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004620 else {
4621 RegionCodeGenTy ThenRCG(ThenCodeGen);
4622 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004623 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004624}
4625
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004626void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4627 const OMPLoopDirective &D,
4628 llvm::Value *TaskFunction,
4629 QualType SharedsTy, Address Shareds,
4630 const Expr *IfCond,
4631 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004632 if (!CGF.HaveInsertPoint())
4633 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004634 TaskResultTy Result =
4635 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004636 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4637 // libcall.
4638 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4639 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4640 // sched, kmp_uint64 grainsize, void *task_dup);
4641 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4642 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4643 llvm::Value *IfVal;
4644 if (IfCond) {
4645 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4646 /*isSigned=*/true);
4647 } else
4648 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4649
4650 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004651 Result.TDBase,
4652 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004653 auto *LBVar =
4654 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4655 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4656 /*IsInitializer=*/true);
4657 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004658 Result.TDBase,
4659 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004660 auto *UBVar =
4661 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4662 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4663 /*IsInitializer=*/true);
4664 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004665 Result.TDBase,
4666 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004667 auto *StVar =
4668 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4669 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4670 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004671 // Store reductions address.
4672 LValue RedLVal = CGF.EmitLValueForField(
4673 Result.TDBase,
4674 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4675 if (Data.Reductions)
4676 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4677 else {
4678 CGF.EmitNullInitialization(RedLVal.getAddress(),
4679 CGF.getContext().VoidPtrTy);
4680 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004681 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004682 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004683 UpLoc,
4684 ThreadID,
4685 Result.NewTask,
4686 IfVal,
4687 LBLVal.getPointer(),
4688 UBLVal.getPointer(),
4689 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4690 llvm::ConstantInt::getNullValue(
4691 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004692 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004693 CGF.IntTy, Data.Schedule.getPointer()
4694 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004695 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004696 Data.Schedule.getPointer()
4697 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004698 /*isSigned=*/false)
4699 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004700 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4701 Result.TaskDupFn, CGF.VoidPtrTy)
4702 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004703 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4704}
4705
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004706/// \brief Emit reduction operation for each element of array (required for
4707/// array sections) LHS op = RHS.
4708/// \param Type Type of array.
4709/// \param LHSVar Variable on the left side of the reduction operation
4710/// (references element of array in original variable).
4711/// \param RHSVar Variable on the right side of the reduction operation
4712/// (references element of array in original variable).
4713/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4714/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004715static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004716 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4717 const VarDecl *RHSVar,
4718 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4719 const Expr *, const Expr *)> &RedOpGen,
4720 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4721 const Expr *UpExpr = nullptr) {
4722 // Perform element-by-element initialization.
4723 QualType ElementTy;
4724 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4725 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4726
4727 // Drill down to the base element type on both arrays.
4728 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4729 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4730
4731 auto RHSBegin = RHSAddr.getPointer();
4732 auto LHSBegin = LHSAddr.getPointer();
4733 // Cast from pointer to array type to pointer to single element.
4734 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4735 // The basic structure here is a while-do loop.
4736 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4737 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4738 auto IsEmpty =
4739 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4740 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4741
4742 // Enter the loop body, making that address the current address.
4743 auto EntryBB = CGF.Builder.GetInsertBlock();
4744 CGF.EmitBlock(BodyBB);
4745
4746 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4747
4748 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4749 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4750 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4751 Address RHSElementCurrent =
4752 Address(RHSElementPHI,
4753 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4754
4755 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4756 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4757 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4758 Address LHSElementCurrent =
4759 Address(LHSElementPHI,
4760 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4761
4762 // Emit copy.
4763 CodeGenFunction::OMPPrivateScope Scope(CGF);
4764 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4765 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4766 Scope.Privatize();
4767 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4768 Scope.ForceCleanup();
4769
4770 // Shift the address forward by one element.
4771 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4772 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4773 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4774 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4775 // Check whether we've reached the end.
4776 auto Done =
4777 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4778 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4779 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4780 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4781
4782 // Done.
4783 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4784}
4785
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004786/// Emit reduction combiner. If the combiner is a simple expression emit it as
4787/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4788/// UDR combiner function.
4789static void emitReductionCombiner(CodeGenFunction &CGF,
4790 const Expr *ReductionOp) {
4791 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4792 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4793 if (auto *DRE =
4794 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4795 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4796 std::pair<llvm::Function *, llvm::Function *> Reduction =
4797 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4798 RValue Func = RValue::get(Reduction.first);
4799 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4800 CGF.EmitIgnoredExpr(ReductionOp);
4801 return;
4802 }
4803 CGF.EmitIgnoredExpr(ReductionOp);
4804}
4805
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004806llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4807 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4808 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4809 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004810 auto &C = CGM.getContext();
4811
4812 // void reduction_func(void *LHSArg, void *RHSArg);
4813 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004814 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4815 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004816 Args.push_back(&LHSArg);
4817 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004818 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004819 auto *Fn = llvm::Function::Create(
4820 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4821 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004822 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004823 CodeGenFunction CGF(CGM);
4824 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4825
4826 // Dst = (void*[n])(LHSArg);
4827 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004828 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4829 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4830 ArgsType), CGF.getPointerAlign());
4831 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4832 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4833 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004834
4835 // ...
4836 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4837 // ...
4838 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004839 auto IPriv = Privates.begin();
4840 unsigned Idx = 0;
4841 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004842 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4843 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004844 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004845 });
4846 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4847 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004848 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004849 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004850 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004851 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004852 // Get array size and emit VLA type.
4853 ++Idx;
4854 Address Elem =
4855 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4856 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004857 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4858 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004859 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004860 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004861 CGF.EmitVariablyModifiedType(PrivTy);
4862 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004863 }
4864 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004865 IPriv = Privates.begin();
4866 auto ILHS = LHSExprs.begin();
4867 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004868 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004869 if ((*IPriv)->getType()->isArrayType()) {
4870 // Emit reduction for array section.
4871 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4872 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004873 EmitOMPAggregateReduction(
4874 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4875 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4876 emitReductionCombiner(CGF, E);
4877 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004878 } else
4879 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004880 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004881 ++IPriv;
4882 ++ILHS;
4883 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004884 }
4885 Scope.ForceCleanup();
4886 CGF.FinishFunction();
4887 return Fn;
4888}
4889
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004890void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4891 const Expr *ReductionOp,
4892 const Expr *PrivateRef,
4893 const DeclRefExpr *LHS,
4894 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004895 if (PrivateRef->getType()->isArrayType()) {
4896 // Emit reduction for array section.
4897 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4898 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4899 EmitOMPAggregateReduction(
4900 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4901 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4902 emitReductionCombiner(CGF, ReductionOp);
4903 });
4904 } else
4905 // Emit reduction for array subscript or single variable.
4906 emitReductionCombiner(CGF, ReductionOp);
4907}
4908
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004909void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004910 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004911 ArrayRef<const Expr *> LHSExprs,
4912 ArrayRef<const Expr *> RHSExprs,
4913 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004914 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004915 if (!CGF.HaveInsertPoint())
4916 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004917
4918 bool WithNowait = Options.WithNowait;
4919 bool SimpleReduction = Options.SimpleReduction;
4920
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004921 // Next code should be emitted for reduction:
4922 //
4923 // static kmp_critical_name lock = { 0 };
4924 //
4925 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4926 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4927 // ...
4928 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4929 // *(Type<n>-1*)rhs[<n>-1]);
4930 // }
4931 //
4932 // ...
4933 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4934 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4935 // RedList, reduce_func, &<lock>)) {
4936 // case 1:
4937 // ...
4938 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4939 // ...
4940 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4941 // break;
4942 // case 2:
4943 // ...
4944 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4945 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004946 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004947 // break;
4948 // default:;
4949 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004950 //
4951 // if SimpleReduction is true, only the next code is generated:
4952 // ...
4953 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4954 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004955
4956 auto &C = CGM.getContext();
4957
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004958 if (SimpleReduction) {
4959 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004960 auto IPriv = Privates.begin();
4961 auto ILHS = LHSExprs.begin();
4962 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004963 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004964 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4965 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004966 ++IPriv;
4967 ++ILHS;
4968 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004969 }
4970 return;
4971 }
4972
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004973 // 1. Build a list of reduction variables.
4974 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004975 auto Size = RHSExprs.size();
4976 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004977 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004978 // Reserve place for array size.
4979 ++Size;
4980 }
4981 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004982 QualType ReductionArrayTy =
4983 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4984 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004985 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004986 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004987 auto IPriv = Privates.begin();
4988 unsigned Idx = 0;
4989 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004990 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004991 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004992 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004993 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004994 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4995 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004996 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004997 // Store array size.
4998 ++Idx;
4999 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5000 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005001 llvm::Value *Size = CGF.Builder.CreateIntCast(
5002 CGF.getVLASize(
5003 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5004 .first,
5005 CGF.SizeTy, /*isSigned=*/false);
5006 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5007 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005008 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005009 }
5010
5011 // 2. Emit reduce_func().
5012 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005013 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5014 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005015
5016 // 3. Create static kmp_critical_name lock = { 0 };
5017 auto *Lock = getCriticalRegionLock(".reduction");
5018
5019 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5020 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005021 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005022 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005023 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005024 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5025 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005026 llvm::Value *Args[] = {
5027 IdentTLoc, // ident_t *<loc>
5028 ThreadId, // i32 <gtid>
5029 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5030 ReductionArrayTySize, // size_type sizeof(RedList)
5031 RL, // void *RedList
5032 ReductionFn, // void (*) (void *, void *) <reduce_func>
5033 Lock // kmp_critical_name *&<lock>
5034 };
5035 auto Res = CGF.EmitRuntimeCall(
5036 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5037 : OMPRTL__kmpc_reduce),
5038 Args);
5039
5040 // 5. Build switch(res)
5041 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5042 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5043
5044 // 6. Build case 1:
5045 // ...
5046 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5047 // ...
5048 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5049 // break;
5050 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5051 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5052 CGF.EmitBlock(Case1BB);
5053
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005054 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5055 llvm::Value *EndArgs[] = {
5056 IdentTLoc, // ident_t *<loc>
5057 ThreadId, // i32 <gtid>
5058 Lock // kmp_critical_name *&<lock>
5059 };
5060 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5061 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005062 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005063 auto IPriv = Privates.begin();
5064 auto ILHS = LHSExprs.begin();
5065 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005066 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005067 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5068 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005069 ++IPriv;
5070 ++ILHS;
5071 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005072 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005073 };
5074 RegionCodeGenTy RCG(CodeGen);
5075 CommonActionTy Action(
5076 nullptr, llvm::None,
5077 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5078 : OMPRTL__kmpc_end_reduce),
5079 EndArgs);
5080 RCG.setAction(Action);
5081 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005082
5083 CGF.EmitBranch(DefaultBB);
5084
5085 // 7. Build case 2:
5086 // ...
5087 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5088 // ...
5089 // break;
5090 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5091 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5092 CGF.EmitBlock(Case2BB);
5093
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005094 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5095 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005096 auto ILHS = LHSExprs.begin();
5097 auto IRHS = RHSExprs.begin();
5098 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005099 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005100 const Expr *XExpr = nullptr;
5101 const Expr *EExpr = nullptr;
5102 const Expr *UpExpr = nullptr;
5103 BinaryOperatorKind BO = BO_Comma;
5104 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5105 if (BO->getOpcode() == BO_Assign) {
5106 XExpr = BO->getLHS();
5107 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005108 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005109 }
5110 // Try to emit update expression as a simple atomic.
5111 auto *RHSExpr = UpExpr;
5112 if (RHSExpr) {
5113 // Analyze RHS part of the whole expression.
5114 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5115 RHSExpr->IgnoreParenImpCasts())) {
5116 // If this is a conditional operator, analyze its condition for
5117 // min/max reduction operator.
5118 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005119 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005120 if (auto *BORHS =
5121 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5122 EExpr = BORHS->getRHS();
5123 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005124 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005125 }
5126 if (XExpr) {
5127 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005128 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005129 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5130 const Expr *EExpr, const Expr *UpExpr) {
5131 LValue X = CGF.EmitLValue(XExpr);
5132 RValue E;
5133 if (EExpr)
5134 E = CGF.EmitAnyExpr(EExpr);
5135 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005136 X, E, BO, /*IsXLHSInRHSPart=*/true,
5137 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005138 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005139 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5140 PrivateScope.addPrivate(
5141 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5142 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5143 CGF.emitOMPSimpleStore(
5144 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5145 VD->getType().getNonReferenceType(), Loc);
5146 return LHSTemp;
5147 });
5148 (void)PrivateScope.Privatize();
5149 return CGF.EmitAnyExpr(UpExpr);
5150 });
5151 };
5152 if ((*IPriv)->getType()->isArrayType()) {
5153 // Emit atomic reduction for array section.
5154 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5155 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5156 AtomicRedGen, XExpr, EExpr, UpExpr);
5157 } else
5158 // Emit atomic reduction for array subscript or single variable.
5159 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5160 } else {
5161 // Emit as a critical region.
5162 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5163 const Expr *, const Expr *) {
5164 auto &RT = CGF.CGM.getOpenMPRuntime();
5165 RT.emitCriticalRegion(
5166 CGF, ".atomic_reduction",
5167 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5168 Action.Enter(CGF);
5169 emitReductionCombiner(CGF, E);
5170 },
5171 Loc);
5172 };
5173 if ((*IPriv)->getType()->isArrayType()) {
5174 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5175 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5176 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5177 CritRedGen);
5178 } else
5179 CritRedGen(CGF, nullptr, nullptr, nullptr);
5180 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005181 ++ILHS;
5182 ++IRHS;
5183 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005184 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005185 };
5186 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5187 if (!WithNowait) {
5188 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5189 llvm::Value *EndArgs[] = {
5190 IdentTLoc, // ident_t *<loc>
5191 ThreadId, // i32 <gtid>
5192 Lock // kmp_critical_name *&<lock>
5193 };
5194 CommonActionTy Action(nullptr, llvm::None,
5195 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5196 EndArgs);
5197 AtomicRCG.setAction(Action);
5198 AtomicRCG(CGF);
5199 } else
5200 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005201
5202 CGF.EmitBranch(DefaultBB);
5203 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5204}
5205
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005206/// Generates unique name for artificial threadprivate variables.
5207/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5208static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5209 unsigned N) {
5210 SmallString<256> Buffer;
5211 llvm::raw_svector_ostream Out(Buffer);
5212 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5213 return Out.str();
5214}
5215
5216/// Emits reduction initializer function:
5217/// \code
5218/// void @.red_init(void* %arg) {
5219/// %0 = bitcast void* %arg to <type>*
5220/// store <type> <init>, <type>* %0
5221/// ret void
5222/// }
5223/// \endcode
5224static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5225 SourceLocation Loc,
5226 ReductionCodeGen &RCG, unsigned N) {
5227 auto &C = CGM.getContext();
5228 FunctionArgList Args;
5229 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5230 Args.emplace_back(&Param);
5231 auto &FnInfo =
5232 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5233 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5234 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5235 ".red_init.", &CGM.getModule());
5236 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5237 CodeGenFunction CGF(CGM);
5238 CGF.disableDebugInfo();
5239 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5240 Address PrivateAddr = CGF.EmitLoadOfPointer(
5241 CGF.GetAddrOfLocalVar(&Param),
5242 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5243 llvm::Value *Size = nullptr;
5244 // If the size of the reduction item is non-constant, load it from global
5245 // threadprivate variable.
5246 if (RCG.getSizes(N).second) {
5247 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5248 CGF, CGM.getContext().getSizeType(),
5249 generateUniqueName("reduction_size", Loc, N));
5250 Size =
5251 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5252 CGM.getContext().getSizeType(), SourceLocation());
5253 }
5254 RCG.emitAggregateType(CGF, N, Size);
5255 LValue SharedLVal;
5256 // If initializer uses initializer from declare reduction construct, emit a
5257 // pointer to the address of the original reduction item (reuired by reduction
5258 // initializer)
5259 if (RCG.usesReductionInitializer(N)) {
5260 Address SharedAddr =
5261 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5262 CGF, CGM.getContext().VoidPtrTy,
5263 generateUniqueName("reduction", Loc, N));
5264 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5265 } else {
5266 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5267 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5268 CGM.getContext().VoidPtrTy);
5269 }
5270 // Emit the initializer:
5271 // %0 = bitcast void* %arg to <type>*
5272 // store <type> <init>, <type>* %0
5273 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5274 [](CodeGenFunction &) { return false; });
5275 CGF.FinishFunction();
5276 return Fn;
5277}
5278
5279/// Emits reduction combiner function:
5280/// \code
5281/// void @.red_comb(void* %arg0, void* %arg1) {
5282/// %lhs = bitcast void* %arg0 to <type>*
5283/// %rhs = bitcast void* %arg1 to <type>*
5284/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5285/// store <type> %2, <type>* %lhs
5286/// ret void
5287/// }
5288/// \endcode
5289static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5290 SourceLocation Loc,
5291 ReductionCodeGen &RCG, unsigned N,
5292 const Expr *ReductionOp,
5293 const Expr *LHS, const Expr *RHS,
5294 const Expr *PrivateRef) {
5295 auto &C = CGM.getContext();
5296 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5297 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5298 FunctionArgList Args;
5299 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5300 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5301 Args.emplace_back(&ParamInOut);
5302 Args.emplace_back(&ParamIn);
5303 auto &FnInfo =
5304 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5305 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5306 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5307 ".red_comb.", &CGM.getModule());
5308 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5309 CodeGenFunction CGF(CGM);
5310 CGF.disableDebugInfo();
5311 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5312 llvm::Value *Size = nullptr;
5313 // If the size of the reduction item is non-constant, load it from global
5314 // threadprivate variable.
5315 if (RCG.getSizes(N).second) {
5316 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5317 CGF, CGM.getContext().getSizeType(),
5318 generateUniqueName("reduction_size", Loc, N));
5319 Size =
5320 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5321 CGM.getContext().getSizeType(), SourceLocation());
5322 }
5323 RCG.emitAggregateType(CGF, N, Size);
5324 // Remap lhs and rhs variables to the addresses of the function arguments.
5325 // %lhs = bitcast void* %arg0 to <type>*
5326 // %rhs = bitcast void* %arg1 to <type>*
5327 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5328 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5329 // Pull out the pointer to the variable.
5330 Address PtrAddr = CGF.EmitLoadOfPointer(
5331 CGF.GetAddrOfLocalVar(&ParamInOut),
5332 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5333 return CGF.Builder.CreateElementBitCast(
5334 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5335 });
5336 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5337 // Pull out the pointer to the variable.
5338 Address PtrAddr = CGF.EmitLoadOfPointer(
5339 CGF.GetAddrOfLocalVar(&ParamIn),
5340 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5341 return CGF.Builder.CreateElementBitCast(
5342 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5343 });
5344 PrivateScope.Privatize();
5345 // Emit the combiner body:
5346 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5347 // store <type> %2, <type>* %lhs
5348 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5349 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5350 cast<DeclRefExpr>(RHS));
5351 CGF.FinishFunction();
5352 return Fn;
5353}
5354
5355/// Emits reduction finalizer function:
5356/// \code
5357/// void @.red_fini(void* %arg) {
5358/// %0 = bitcast void* %arg to <type>*
5359/// <destroy>(<type>* %0)
5360/// ret void
5361/// }
5362/// \endcode
5363static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5364 SourceLocation Loc,
5365 ReductionCodeGen &RCG, unsigned N) {
5366 if (!RCG.needCleanups(N))
5367 return nullptr;
5368 auto &C = CGM.getContext();
5369 FunctionArgList Args;
5370 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5371 Args.emplace_back(&Param);
5372 auto &FnInfo =
5373 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5374 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5375 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5376 ".red_fini.", &CGM.getModule());
5377 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5378 CodeGenFunction CGF(CGM);
5379 CGF.disableDebugInfo();
5380 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5381 Address PrivateAddr = CGF.EmitLoadOfPointer(
5382 CGF.GetAddrOfLocalVar(&Param),
5383 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5384 llvm::Value *Size = nullptr;
5385 // If the size of the reduction item is non-constant, load it from global
5386 // threadprivate variable.
5387 if (RCG.getSizes(N).second) {
5388 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5389 CGF, CGM.getContext().getSizeType(),
5390 generateUniqueName("reduction_size", Loc, N));
5391 Size =
5392 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5393 CGM.getContext().getSizeType(), SourceLocation());
5394 }
5395 RCG.emitAggregateType(CGF, N, Size);
5396 // Emit the finalizer body:
5397 // <destroy>(<type>* %0)
5398 RCG.emitCleanups(CGF, N, PrivateAddr);
5399 CGF.FinishFunction();
5400 return Fn;
5401}
5402
5403llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5404 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5405 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5406 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5407 return nullptr;
5408
5409 // Build typedef struct:
5410 // kmp_task_red_input {
5411 // void *reduce_shar; // shared reduction item
5412 // size_t reduce_size; // size of data item
5413 // void *reduce_init; // data initialization routine
5414 // void *reduce_fini; // data finalization routine
5415 // void *reduce_comb; // data combiner routine
5416 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5417 // } kmp_task_red_input_t;
5418 ASTContext &C = CGM.getContext();
5419 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5420 RD->startDefinition();
5421 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5422 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5423 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5424 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5425 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5426 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5427 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5428 RD->completeDefinition();
5429 QualType RDType = C.getRecordType(RD);
5430 unsigned Size = Data.ReductionVars.size();
5431 llvm::APInt ArraySize(/*numBits=*/64, Size);
5432 QualType ArrayRDType = C.getConstantArrayType(
5433 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5434 // kmp_task_red_input_t .rd_input.[Size];
5435 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5436 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5437 Data.ReductionOps);
5438 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5439 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5440 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5441 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5442 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5443 TaskRedInput.getPointer(), Idxs,
5444 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5445 ".rd_input.gep.");
5446 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5447 // ElemLVal.reduce_shar = &Shareds[Cnt];
5448 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5449 RCG.emitSharedLValue(CGF, Cnt);
5450 llvm::Value *CastedShared =
5451 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5452 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5453 RCG.emitAggregateType(CGF, Cnt);
5454 llvm::Value *SizeValInChars;
5455 llvm::Value *SizeVal;
5456 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5457 // We use delayed creation/initialization for VLAs, array sections and
5458 // custom reduction initializations. It is required because runtime does not
5459 // provide the way to pass the sizes of VLAs/array sections to
5460 // initializer/combiner/finalizer functions and does not pass the pointer to
5461 // original reduction item to the initializer. Instead threadprivate global
5462 // variables are used to store these values and use them in the functions.
5463 bool DelayedCreation = !!SizeVal;
5464 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5465 /*isSigned=*/false);
5466 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5467 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5468 // ElemLVal.reduce_init = init;
5469 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5470 llvm::Value *InitAddr =
5471 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5472 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5473 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5474 // ElemLVal.reduce_fini = fini;
5475 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5476 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5477 llvm::Value *FiniAddr = Fini
5478 ? CGF.EmitCastToVoidPtr(Fini)
5479 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5480 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5481 // ElemLVal.reduce_comb = comb;
5482 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5483 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5484 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5485 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5486 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5487 // ElemLVal.flags = 0;
5488 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5489 if (DelayedCreation) {
5490 CGF.EmitStoreOfScalar(
5491 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5492 FlagsLVal);
5493 } else
5494 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5495 }
5496 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5497 // *data);
5498 llvm::Value *Args[] = {
5499 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5500 /*isSigned=*/true),
5501 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5502 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5503 CGM.VoidPtrTy)};
5504 return CGF.EmitRuntimeCall(
5505 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5506}
5507
5508void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5509 SourceLocation Loc,
5510 ReductionCodeGen &RCG,
5511 unsigned N) {
5512 auto Sizes = RCG.getSizes(N);
5513 // Emit threadprivate global variable if the type is non-constant
5514 // (Sizes.second = nullptr).
5515 if (Sizes.second) {
5516 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5517 /*isSigned=*/false);
5518 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5519 CGF, CGM.getContext().getSizeType(),
5520 generateUniqueName("reduction_size", Loc, N));
5521 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5522 }
5523 // Store address of the original reduction item if custom initializer is used.
5524 if (RCG.usesReductionInitializer(N)) {
5525 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5526 CGF, CGM.getContext().VoidPtrTy,
5527 generateUniqueName("reduction", Loc, N));
5528 CGF.Builder.CreateStore(
5529 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5530 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5531 SharedAddr, /*IsVolatile=*/false);
5532 }
5533}
5534
5535Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5536 SourceLocation Loc,
5537 llvm::Value *ReductionsPtr,
5538 LValue SharedLVal) {
5539 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5540 // *d);
5541 llvm::Value *Args[] = {
5542 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5543 /*isSigned=*/true),
5544 ReductionsPtr,
5545 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5546 CGM.VoidPtrTy)};
5547 return Address(
5548 CGF.EmitRuntimeCall(
5549 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5550 SharedLVal.getAlignment());
5551}
5552
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005553void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5554 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005555 if (!CGF.HaveInsertPoint())
5556 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005557 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5558 // global_tid);
5559 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5560 // Ignore return result until untied tasks are supported.
5561 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005562 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5563 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005564}
5565
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005566void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005567 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005568 const RegionCodeGenTy &CodeGen,
5569 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005570 if (!CGF.HaveInsertPoint())
5571 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005572 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005573 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005574}
5575
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005576namespace {
5577enum RTCancelKind {
5578 CancelNoreq = 0,
5579 CancelParallel = 1,
5580 CancelLoop = 2,
5581 CancelSections = 3,
5582 CancelTaskgroup = 4
5583};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005584} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005585
5586static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5587 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005588 if (CancelRegion == OMPD_parallel)
5589 CancelKind = CancelParallel;
5590 else if (CancelRegion == OMPD_for)
5591 CancelKind = CancelLoop;
5592 else if (CancelRegion == OMPD_sections)
5593 CancelKind = CancelSections;
5594 else {
5595 assert(CancelRegion == OMPD_taskgroup);
5596 CancelKind = CancelTaskgroup;
5597 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005598 return CancelKind;
5599}
5600
5601void CGOpenMPRuntime::emitCancellationPointCall(
5602 CodeGenFunction &CGF, SourceLocation Loc,
5603 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005604 if (!CGF.HaveInsertPoint())
5605 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005606 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5607 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005608 if (auto *OMPRegionInfo =
5609 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005610 // For 'cancellation point taskgroup', the task region info may not have a
5611 // cancel. This may instead happen in another adjacent task.
5612 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005613 llvm::Value *Args[] = {
5614 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5615 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005616 // Ignore return result until untied tasks are supported.
5617 auto *Result = CGF.EmitRuntimeCall(
5618 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5619 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005620 // exit from construct;
5621 // }
5622 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5623 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5624 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5625 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5626 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005627 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005628 auto CancelDest =
5629 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005630 CGF.EmitBranchThroughCleanup(CancelDest);
5631 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5632 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005633 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005634}
5635
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005636void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005637 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005638 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005639 if (!CGF.HaveInsertPoint())
5640 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005641 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5642 // kmp_int32 cncl_kind);
5643 if (auto *OMPRegionInfo =
5644 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005645 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5646 PrePostActionTy &) {
5647 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005648 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005649 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005650 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5651 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005652 auto *Result = CGF.EmitRuntimeCall(
5653 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005654 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005655 // exit from construct;
5656 // }
5657 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5658 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5659 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5660 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5661 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005662 // exit from construct;
5663 auto CancelDest =
5664 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5665 CGF.EmitBranchThroughCleanup(CancelDest);
5666 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5667 };
5668 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005669 emitOMPIfClause(CGF, IfCond, ThenGen,
5670 [](CodeGenFunction &, PrePostActionTy &) {});
5671 else {
5672 RegionCodeGenTy ThenRCG(ThenGen);
5673 ThenRCG(CGF);
5674 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005675 }
5676}
Samuel Antaobed3c462015-10-02 16:14:20 +00005677
Samuel Antaoee8fb302016-01-06 13:42:12 +00005678/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005679/// consists of the file and device IDs as well as line number associated with
5680/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005681static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5682 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005683 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005684
5685 auto &SM = C.getSourceManager();
5686
5687 // The loc should be always valid and have a file ID (the user cannot use
5688 // #pragma directives in macros)
5689
5690 assert(Loc.isValid() && "Source location is expected to be always valid.");
5691 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5692
5693 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5694 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5695
5696 llvm::sys::fs::UniqueID ID;
5697 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5698 llvm_unreachable("Source file with target region no longer exists!");
5699
5700 DeviceID = ID.getDevice();
5701 FileID = ID.getFile();
5702 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005703}
5704
5705void CGOpenMPRuntime::emitTargetOutlinedFunction(
5706 const OMPExecutableDirective &D, StringRef ParentName,
5707 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005708 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005709 assert(!ParentName.empty() && "Invalid target region parent name!");
5710
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005711 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5712 IsOffloadEntry, CodeGen);
5713}
5714
5715void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5716 const OMPExecutableDirective &D, StringRef ParentName,
5717 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5718 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005719 // Create a unique name for the entry function using the source location
5720 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005721 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005722 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005723 //
5724 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005725 // mangled name of the function that encloses the target region and BB is the
5726 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005727
5728 unsigned DeviceID;
5729 unsigned FileID;
5730 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005731 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005732 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005733 SmallString<64> EntryFnName;
5734 {
5735 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005736 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5737 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005738 }
5739
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005740 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5741
Samuel Antaobed3c462015-10-02 16:14:20 +00005742 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005743 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005744 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005745
Samuel Antao6d004262016-06-16 18:39:34 +00005746 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005747
5748 // If this target outline function is not an offload entry, we don't need to
5749 // register it.
5750 if (!IsOffloadEntry)
5751 return;
5752
5753 // The target region ID is used by the runtime library to identify the current
5754 // target region, so it only has to be unique and not necessarily point to
5755 // anything. It could be the pointer to the outlined function that implements
5756 // the target region, but we aren't using that so that the compiler doesn't
5757 // need to keep that, and could therefore inline the host function if proven
5758 // worthwhile during optimization. In the other hand, if emitting code for the
5759 // device, the ID has to be the function address so that it can retrieved from
5760 // the offloading entry and launched by the runtime library. We also mark the
5761 // outlined function to have external linkage in case we are emitting code for
5762 // the device, because these functions will be entry points to the device.
5763
5764 if (CGM.getLangOpts().OpenMPIsDevice) {
5765 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5766 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5767 } else
5768 OutlinedFnID = new llvm::GlobalVariable(
5769 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5770 llvm::GlobalValue::PrivateLinkage,
5771 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5772
5773 // Register the information for the entry associated with this target region.
5774 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005775 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5776 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005777}
5778
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005779/// discard all CompoundStmts intervening between two constructs
5780static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5781 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5782 Body = CS->body_front();
5783
5784 return Body;
5785}
5786
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005787/// Emit the number of teams for a target directive. Inspect the num_teams
5788/// clause associated with a teams construct combined or closely nested
5789/// with the target directive.
5790///
5791/// Emit a team of size one for directives such as 'target parallel' that
5792/// have no associated teams construct.
5793///
5794/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005795static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005796emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5797 CodeGenFunction &CGF,
5798 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005799
5800 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5801 "teams directive expected to be "
5802 "emitted only for the host!");
5803
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005804 auto &Bld = CGF.Builder;
5805
5806 // If the target directive is combined with a teams directive:
5807 // Return the value in the num_teams clause, if any.
5808 // Otherwise, return 0 to denote the runtime default.
5809 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5810 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5811 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5812 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5813 /*IgnoreResultAssign*/ true);
5814 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5815 /*IsSigned=*/true);
5816 }
5817
5818 // The default value is 0.
5819 return Bld.getInt32(0);
5820 }
5821
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005822 // If the target directive is combined with a parallel directive but not a
5823 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005824 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5825 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005826
5827 // If the current target region has a teams region enclosed, we need to get
5828 // the number of teams to pass to the runtime function call. This is done
5829 // by generating the expression in a inlined region. This is required because
5830 // the expression is captured in the enclosing target environment when the
5831 // teams directive is not combined with target.
5832
5833 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5834
5835 // FIXME: Accommodate other combined directives with teams when they become
5836 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005837 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5838 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005839 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5840 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5841 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5842 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005843 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5844 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005845 }
5846
5847 // If we have an enclosed teams directive but no num_teams clause we use
5848 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005849 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005850 }
5851
5852 // No teams associated with the directive.
5853 return nullptr;
5854}
5855
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005856/// Emit the number of threads for a target directive. Inspect the
5857/// thread_limit clause associated with a teams construct combined or closely
5858/// nested with the target directive.
5859///
5860/// Emit the num_threads clause for directives such as 'target parallel' that
5861/// have no associated teams construct.
5862///
5863/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005864static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005865emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5866 CodeGenFunction &CGF,
5867 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005868
5869 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5870 "teams directive expected to be "
5871 "emitted only for the host!");
5872
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005873 auto &Bld = CGF.Builder;
5874
5875 //
5876 // If the target directive is combined with a teams directive:
5877 // Return the value in the thread_limit clause, if any.
5878 //
5879 // If the target directive is combined with a parallel directive:
5880 // Return the value in the num_threads clause, if any.
5881 //
5882 // If both clauses are set, select the minimum of the two.
5883 //
5884 // If neither teams or parallel combined directives set the number of threads
5885 // in a team, return 0 to denote the runtime default.
5886 //
5887 // If this is not a teams directive return nullptr.
5888
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005889 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5890 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005891 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5892 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005893 llvm::Value *ThreadLimitVal = nullptr;
5894
5895 if (const auto *ThreadLimitClause =
5896 D.getSingleClause<OMPThreadLimitClause>()) {
5897 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5898 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5899 /*IgnoreResultAssign*/ true);
5900 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5901 /*IsSigned=*/true);
5902 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005903
5904 if (const auto *NumThreadsClause =
5905 D.getSingleClause<OMPNumThreadsClause>()) {
5906 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5907 llvm::Value *NumThreads =
5908 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5909 /*IgnoreResultAssign*/ true);
5910 NumThreadsVal =
5911 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5912 }
5913
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005914 // Select the lesser of thread_limit and num_threads.
5915 if (NumThreadsVal)
5916 ThreadLimitVal = ThreadLimitVal
5917 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5918 ThreadLimitVal),
5919 NumThreadsVal, ThreadLimitVal)
5920 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005921
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005922 // Set default value passed to the runtime if either teams or a target
5923 // parallel type directive is found but no clause is specified.
5924 if (!ThreadLimitVal)
5925 ThreadLimitVal = DefaultThreadLimitVal;
5926
5927 return ThreadLimitVal;
5928 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005929
Samuel Antaob68e2db2016-03-03 16:20:23 +00005930 // If the current target region has a teams region enclosed, we need to get
5931 // the thread limit to pass to the runtime function call. This is done
5932 // by generating the expression in a inlined region. This is required because
5933 // the expression is captured in the enclosing target environment when the
5934 // teams directive is not combined with target.
5935
5936 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5937
5938 // FIXME: Accommodate other combined directives with teams when they become
5939 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005940 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5941 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005942 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5943 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5944 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5945 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5946 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5947 /*IsSigned=*/true);
5948 }
5949
5950 // If we have an enclosed teams directive but no thread_limit clause we use
5951 // the default value 0.
5952 return CGF.Builder.getInt32(0);
5953 }
5954
5955 // No teams associated with the directive.
5956 return nullptr;
5957}
5958
Samuel Antao86ace552016-04-27 22:40:57 +00005959namespace {
5960// \brief Utility to handle information from clauses associated with a given
5961// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5962// It provides a convenient interface to obtain the information and generate
5963// code for that information.
5964class MappableExprsHandler {
5965public:
5966 /// \brief Values for bit flags used to specify the mapping type for
5967 /// offloading.
5968 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005969 /// \brief Allocate memory on the device and move data from host to device.
5970 OMP_MAP_TO = 0x01,
5971 /// \brief Allocate memory on the device and move data from device to host.
5972 OMP_MAP_FROM = 0x02,
5973 /// \brief Always perform the requested mapping action on the element, even
5974 /// if it was already mapped before.
5975 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005976 /// \brief Delete the element from the device environment, ignoring the
5977 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005978 OMP_MAP_DELETE = 0x08,
5979 /// \brief The element being mapped is a pointer, therefore the pointee
5980 /// should be mapped as well.
5981 OMP_MAP_IS_PTR = 0x10,
5982 /// \brief This flags signals that an argument is the first one relating to
5983 /// a map/private clause expression. For some cases a single
5984 /// map/privatization results in multiple arguments passed to the runtime
5985 /// library.
5986 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005987 /// \brief Signal that the runtime library has to return the device pointer
5988 /// in the current position for the data being mapped.
5989 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005990 /// \brief This flag signals that the reference being passed is a pointer to
5991 /// private data.
5992 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005993 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005994 OMP_MAP_PRIVATE_VAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00005995 /// Implicit map
5996 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00005997 };
5998
Samuel Antaocc10b852016-07-28 14:23:26 +00005999 /// Class that associates information with a base pointer to be passed to the
6000 /// runtime library.
6001 class BasePointerInfo {
6002 /// The base pointer.
6003 llvm::Value *Ptr = nullptr;
6004 /// The base declaration that refers to this device pointer, or null if
6005 /// there is none.
6006 const ValueDecl *DevPtrDecl = nullptr;
6007
6008 public:
6009 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6010 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6011 llvm::Value *operator*() const { return Ptr; }
6012 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6013 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6014 };
6015
6016 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006017 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
6018 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
6019
6020private:
6021 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006022 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006023
6024 /// \brief Function the directive is being generated for.
6025 CodeGenFunction &CGF;
6026
Samuel Antaod486f842016-05-26 16:53:38 +00006027 /// \brief Set of all first private variables in the current directive.
6028 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6029
Samuel Antao6890b092016-07-28 14:25:09 +00006030 /// Map between device pointer declarations and their expression components.
6031 /// The key value for declarations in 'this' is null.
6032 llvm::DenseMap<
6033 const ValueDecl *,
6034 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6035 DevPointersMap;
6036
Samuel Antao86ace552016-04-27 22:40:57 +00006037 llvm::Value *getExprTypeSize(const Expr *E) const {
6038 auto ExprTy = E->getType().getCanonicalType();
6039
6040 // Reference types are ignored for mapping purposes.
6041 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6042 ExprTy = RefTy->getPointeeType().getCanonicalType();
6043
6044 // Given that an array section is considered a built-in type, we need to
6045 // do the calculation based on the length of the section instead of relying
6046 // on CGF.getTypeSize(E->getType()).
6047 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6048 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6049 OAE->getBase()->IgnoreParenImpCasts())
6050 .getCanonicalType();
6051
6052 // If there is no length associated with the expression, that means we
6053 // are using the whole length of the base.
6054 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6055 return CGF.getTypeSize(BaseTy);
6056
6057 llvm::Value *ElemSize;
6058 if (auto *PTy = BaseTy->getAs<PointerType>())
6059 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6060 else {
6061 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6062 assert(ATy && "Expecting array type if not a pointer type.");
6063 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6064 }
6065
6066 // If we don't have a length at this point, that is because we have an
6067 // array section with a single element.
6068 if (!OAE->getLength())
6069 return ElemSize;
6070
6071 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6072 LengthVal =
6073 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6074 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6075 }
6076 return CGF.getTypeSize(ExprTy);
6077 }
6078
6079 /// \brief Return the corresponding bits for a given map clause modifier. Add
6080 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006081 /// map as the first one of a series of maps that relate to the same map
6082 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006083 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6084 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006085 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006086 unsigned Bits = 0u;
6087 switch (MapType) {
6088 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006089 case OMPC_MAP_release:
6090 // alloc and release is the default behavior in the runtime library, i.e.
6091 // if we don't pass any bits alloc/release that is what the runtime is
6092 // going to do. Therefore, we don't need to signal anything for these two
6093 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006094 break;
6095 case OMPC_MAP_to:
6096 Bits = OMP_MAP_TO;
6097 break;
6098 case OMPC_MAP_from:
6099 Bits = OMP_MAP_FROM;
6100 break;
6101 case OMPC_MAP_tofrom:
6102 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6103 break;
6104 case OMPC_MAP_delete:
6105 Bits = OMP_MAP_DELETE;
6106 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006107 default:
6108 llvm_unreachable("Unexpected map type!");
6109 break;
6110 }
6111 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006112 Bits |= OMP_MAP_IS_PTR;
6113 if (AddIsFirstFlag)
6114 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006115 if (MapTypeModifier == OMPC_MAP_always)
6116 Bits |= OMP_MAP_ALWAYS;
6117 return Bits;
6118 }
6119
6120 /// \brief Return true if the provided expression is a final array section. A
6121 /// final array section, is one whose length can't be proved to be one.
6122 bool isFinalArraySectionExpression(const Expr *E) const {
6123 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6124
6125 // It is not an array section and therefore not a unity-size one.
6126 if (!OASE)
6127 return false;
6128
6129 // An array section with no colon always refer to a single element.
6130 if (OASE->getColonLoc().isInvalid())
6131 return false;
6132
6133 auto *Length = OASE->getLength();
6134
6135 // If we don't have a length we have to check if the array has size 1
6136 // for this dimension. Also, we should always expect a length if the
6137 // base type is pointer.
6138 if (!Length) {
6139 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6140 OASE->getBase()->IgnoreParenImpCasts())
6141 .getCanonicalType();
6142 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6143 return ATy->getSize().getSExtValue() != 1;
6144 // If we don't have a constant dimension length, we have to consider
6145 // the current section as having any size, so it is not necessarily
6146 // unitary. If it happen to be unity size, that's user fault.
6147 return true;
6148 }
6149
6150 // Check if the length evaluates to 1.
6151 llvm::APSInt ConstLength;
6152 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6153 return true; // Can have more that size 1.
6154
6155 return ConstLength.getSExtValue() != 1;
6156 }
6157
6158 /// \brief Generate the base pointers, section pointers, sizes and map type
6159 /// bits for the provided map type, map modifier, and expression components.
6160 /// \a IsFirstComponent should be set to true if the provided set of
6161 /// components is the first associated with a capture.
6162 void generateInfoForComponentList(
6163 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6164 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006165 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006166 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006167 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006168
6169 // The following summarizes what has to be generated for each map and the
6170 // types bellow. The generated information is expressed in this order:
6171 // base pointer, section pointer, size, flags
6172 // (to add to the ones that come from the map type and modifier).
6173 //
6174 // double d;
6175 // int i[100];
6176 // float *p;
6177 //
6178 // struct S1 {
6179 // int i;
6180 // float f[50];
6181 // }
6182 // struct S2 {
6183 // int i;
6184 // float f[50];
6185 // S1 s;
6186 // double *p;
6187 // struct S2 *ps;
6188 // }
6189 // S2 s;
6190 // S2 *ps;
6191 //
6192 // map(d)
6193 // &d, &d, sizeof(double), noflags
6194 //
6195 // map(i)
6196 // &i, &i, 100*sizeof(int), noflags
6197 //
6198 // map(i[1:23])
6199 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6200 //
6201 // map(p)
6202 // &p, &p, sizeof(float*), noflags
6203 //
6204 // map(p[1:24])
6205 // p, &p[1], 24*sizeof(float), noflags
6206 //
6207 // map(s)
6208 // &s, &s, sizeof(S2), noflags
6209 //
6210 // map(s.i)
6211 // &s, &(s.i), sizeof(int), noflags
6212 //
6213 // map(s.s.f)
6214 // &s, &(s.i.f), 50*sizeof(int), noflags
6215 //
6216 // map(s.p)
6217 // &s, &(s.p), sizeof(double*), noflags
6218 //
6219 // map(s.p[:22], s.a s.b)
6220 // &s, &(s.p), sizeof(double*), noflags
6221 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6222 //
6223 // map(s.ps)
6224 // &s, &(s.ps), sizeof(S2*), noflags
6225 //
6226 // map(s.ps->s.i)
6227 // &s, &(s.ps), sizeof(S2*), noflags
6228 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6229 //
6230 // map(s.ps->ps)
6231 // &s, &(s.ps), sizeof(S2*), noflags
6232 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6233 //
6234 // map(s.ps->ps->ps)
6235 // &s, &(s.ps), sizeof(S2*), noflags
6236 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6237 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6238 //
6239 // map(s.ps->ps->s.f[:22])
6240 // &s, &(s.ps), sizeof(S2*), noflags
6241 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6242 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6243 //
6244 // map(ps)
6245 // &ps, &ps, sizeof(S2*), noflags
6246 //
6247 // map(ps->i)
6248 // ps, &(ps->i), sizeof(int), noflags
6249 //
6250 // map(ps->s.f)
6251 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6252 //
6253 // map(ps->p)
6254 // ps, &(ps->p), sizeof(double*), noflags
6255 //
6256 // map(ps->p[:22])
6257 // ps, &(ps->p), sizeof(double*), noflags
6258 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6259 //
6260 // map(ps->ps)
6261 // ps, &(ps->ps), sizeof(S2*), noflags
6262 //
6263 // map(ps->ps->s.i)
6264 // ps, &(ps->ps), sizeof(S2*), noflags
6265 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6266 //
6267 // map(ps->ps->ps)
6268 // ps, &(ps->ps), sizeof(S2*), noflags
6269 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6270 //
6271 // map(ps->ps->ps->ps)
6272 // ps, &(ps->ps), sizeof(S2*), noflags
6273 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6274 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6275 //
6276 // map(ps->ps->ps->s.f[:22])
6277 // ps, &(ps->ps), sizeof(S2*), noflags
6278 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6279 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6280 // extra_flag
6281
6282 // Track if the map information being generated is the first for a capture.
6283 bool IsCaptureFirstInfo = IsFirstComponentList;
6284
6285 // Scan the components from the base to the complete expression.
6286 auto CI = Components.rbegin();
6287 auto CE = Components.rend();
6288 auto I = CI;
6289
6290 // Track if the map information being generated is the first for a list of
6291 // components.
6292 bool IsExpressionFirstInfo = true;
6293 llvm::Value *BP = nullptr;
6294
6295 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6296 // The base is the 'this' pointer. The content of the pointer is going
6297 // to be the base of the field being mapped.
6298 BP = CGF.EmitScalarExpr(ME->getBase());
6299 } else {
6300 // The base is the reference to the variable.
6301 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006302 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006303
6304 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006305 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006306 // reference. References are ignored for mapping purposes.
6307 QualType Ty =
6308 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6309 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6310 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006311 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006312 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006313 .getPointer();
6314
6315 // We do not need to generate individual map information for the
6316 // pointer, it can be associated with the combined storage.
6317 ++I;
6318 }
6319 }
6320
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006321 unsigned DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006322 for (; I != CE; ++I) {
6323 auto Next = std::next(I);
6324
6325 // We need to generate the addresses and sizes if this is the last
6326 // component, if the component is a pointer or if it is an array section
6327 // whose length can't be proved to be one. If this is a pointer, it
6328 // becomes the base address for the following components.
6329
6330 // A final array section, is one whose length can't be proved to be one.
6331 bool IsFinalArraySection =
6332 isFinalArraySectionExpression(I->getAssociatedExpression());
6333
6334 // Get information on whether the element is a pointer. Have to do a
6335 // special treatment for array sections given that they are built-in
6336 // types.
6337 const auto *OASE =
6338 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6339 bool IsPointer =
6340 (OASE &&
6341 OMPArraySectionExpr::getBaseOriginalType(OASE)
6342 .getCanonicalType()
6343 ->isAnyPointerType()) ||
6344 I->getAssociatedExpression()->getType()->isAnyPointerType();
6345
6346 if (Next == CE || IsPointer || IsFinalArraySection) {
6347
6348 // If this is not the last component, we expect the pointer to be
6349 // associated with an array expression or member expression.
6350 assert((Next == CE ||
6351 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6352 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6353 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6354 "Unexpected expression");
6355
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006356 llvm::Value *LB =
6357 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006358 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6359
Samuel Antao03a3cec2016-07-27 22:52:16 +00006360 // If we have a member expression and the current component is a
6361 // reference, we have to map the reference too. Whenever we have a
6362 // reference, the section that reference refers to is going to be a
6363 // load instruction from the storage assigned to the reference.
6364 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6365 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6366 auto *LI = cast<llvm::LoadInst>(LB);
6367 auto *RefAddr = LI->getPointerOperand();
6368
6369 BasePointers.push_back(BP);
6370 Pointers.push_back(RefAddr);
6371 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006372 Types.push_back(DefaultFlags |
6373 getMapTypeBits(
6374 /*MapType*/ OMPC_MAP_alloc,
6375 /*MapTypeModifier=*/OMPC_MAP_unknown,
6376 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006377 IsExpressionFirstInfo = false;
6378 IsCaptureFirstInfo = false;
6379 // The reference will be the next base address.
6380 BP = RefAddr;
6381 }
6382
6383 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006384 Pointers.push_back(LB);
6385 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006386
Samuel Antao6782e942016-05-26 16:48:10 +00006387 // We need to add a pointer flag for each map that comes from the
6388 // same expression except for the first one. We also need to signal
6389 // this map is the first one that relates with the current capture
6390 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006391 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6392 !IsExpressionFirstInfo,
6393 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006394
6395 // If we have a final array section, we are done with this expression.
6396 if (IsFinalArraySection)
6397 break;
6398
6399 // The pointer becomes the base for the next element.
6400 if (Next != CE)
6401 BP = LB;
6402
6403 IsExpressionFirstInfo = false;
6404 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006405 }
6406 }
6407 }
6408
Samuel Antaod486f842016-05-26 16:53:38 +00006409 /// \brief Return the adjusted map modifiers if the declaration a capture
6410 /// refers to appears in a first-private clause. This is expected to be used
6411 /// only with directives that start with 'target'.
6412 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6413 unsigned CurrentModifiers) {
6414 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6415
6416 // A first private variable captured by reference will use only the
6417 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6418 // declaration is known as first-private in this handler.
6419 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6420 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6421 MappableExprsHandler::OMP_MAP_TO;
6422
6423 // We didn't modify anything.
6424 return CurrentModifiers;
6425 }
6426
Samuel Antao86ace552016-04-27 22:40:57 +00006427public:
6428 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006429 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006430 // Extract firstprivate clause information.
6431 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6432 for (const auto *D : C->varlists())
6433 FirstPrivateDecls.insert(
6434 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006435 // Extract device pointer clause information.
6436 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6437 for (auto L : C->component_lists())
6438 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006439 }
Samuel Antao86ace552016-04-27 22:40:57 +00006440
6441 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006442 /// types for the extracted mappable expressions. Also, for each item that
6443 /// relates with a device pointer, a pair of the relevant declaration and
6444 /// index where it occurs is appended to the device pointers info array.
6445 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006446 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6447 MapFlagsArrayTy &Types) const {
6448 BasePointers.clear();
6449 Pointers.clear();
6450 Sizes.clear();
6451 Types.clear();
6452
6453 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006454 /// Kind that defines how a device pointer has to be returned.
6455 enum ReturnPointerKind {
6456 // Don't have to return any pointer.
6457 RPK_None,
6458 // Pointer is the base of the declaration.
6459 RPK_Base,
6460 // Pointer is a member of the base declaration - 'this'
6461 RPK_Member,
6462 // Pointer is a reference and a member of the base declaration - 'this'
6463 RPK_MemberReference,
6464 };
Samuel Antao86ace552016-04-27 22:40:57 +00006465 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006466 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6467 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6468 ReturnPointerKind ReturnDevicePointer = RPK_None;
6469 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006470
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006471 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006472 MapInfo(
6473 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6474 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006475 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006476 : Components(Components), MapType(MapType),
6477 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006478 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006479 };
6480
6481 // We have to process the component lists that relate with the same
6482 // declaration in a single chunk so that we can generate the map flags
6483 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006484 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006485
6486 // Helper function to fill the information map for the different supported
6487 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006488 auto &&InfoGen = [&Info](
6489 const ValueDecl *D,
6490 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6491 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006492 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006493 const ValueDecl *VD =
6494 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006495 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6496 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006497 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006498
Paul Robinson78fb1322016-08-01 22:12:46 +00006499 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006500 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006501 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006502 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006503 MapInfo::RPK_None, C->isImplicit());
6504 }
Paul Robinson15c84002016-07-29 20:46:16 +00006505 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006506 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006507 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006508 MapInfo::RPK_None, C->isImplicit());
6509 }
Paul Robinson15c84002016-07-29 20:46:16 +00006510 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006511 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006512 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006513 MapInfo::RPK_None, C->isImplicit());
6514 }
Samuel Antao86ace552016-04-27 22:40:57 +00006515
Samuel Antaocc10b852016-07-28 14:23:26 +00006516 // Look at the use_device_ptr clause information and mark the existing map
6517 // entries as such. If there is no map information for an entry in the
6518 // use_device_ptr list, we create one with map type 'alloc' and zero size
6519 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006520 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006521 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006522 for (auto L : C->component_lists()) {
6523 assert(!L.second.empty() && "Not expecting empty list of components!");
6524 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6525 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6526 auto *IE = L.second.back().getAssociatedExpression();
6527 // If the first component is a member expression, we have to look into
6528 // 'this', which maps to null in the map of map information. Otherwise
6529 // look directly for the information.
6530 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6531
6532 // We potentially have map information for this declaration already.
6533 // Look for the first set of components that refer to it.
6534 if (It != Info.end()) {
6535 auto CI = std::find_if(
6536 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6537 return MI.Components.back().getAssociatedDeclaration() == VD;
6538 });
6539 // If we found a map entry, signal that the pointer has to be returned
6540 // and move on to the next declaration.
6541 if (CI != It->second.end()) {
6542 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6543 ? (VD->getType()->isReferenceType()
6544 ? MapInfo::RPK_MemberReference
6545 : MapInfo::RPK_Member)
6546 : MapInfo::RPK_Base;
6547 continue;
6548 }
6549 }
6550
6551 // We didn't find any match in our map information - generate a zero
6552 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006553 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006554 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006555 this->CGF
6556 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006557 .getScalarVal();
6558 BasePointers.push_back({Ptr, VD});
6559 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006560 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006561 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6562 }
6563
Samuel Antao86ace552016-04-27 22:40:57 +00006564 for (auto &M : Info) {
6565 // We need to know when we generate information for the first component
6566 // associated with a capture, because the mapping flags depend on it.
6567 bool IsFirstComponentList = true;
6568 for (MapInfo &L : M.second) {
6569 assert(!L.Components.empty() &&
6570 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006571
6572 // Remember the current base pointer index.
6573 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006574 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006575 this->generateInfoForComponentList(
6576 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6577 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006578
6579 // If this entry relates with a device pointer, set the relevant
6580 // declaration and add the 'return pointer' flag.
6581 if (IsFirstComponentList &&
6582 L.ReturnDevicePointer != MapInfo::RPK_None) {
6583 // If the pointer is not the base of the map, we need to skip the
6584 // base. If it is a reference in a member field, we also need to skip
6585 // the map of the reference.
6586 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6587 ++CurrentBasePointersIdx;
6588 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6589 ++CurrentBasePointersIdx;
6590 }
6591 assert(BasePointers.size() > CurrentBasePointersIdx &&
6592 "Unexpected number of mapped base pointers.");
6593
6594 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6595 assert(RelevantVD &&
6596 "No relevant declaration related with device pointer??");
6597
6598 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6599 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6600 }
Samuel Antao86ace552016-04-27 22:40:57 +00006601 IsFirstComponentList = false;
6602 }
6603 }
6604 }
6605
6606 /// \brief Generate the base pointers, section pointers, sizes and map types
6607 /// associated to a given capture.
6608 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006609 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006610 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006611 MapValuesArrayTy &Pointers,
6612 MapValuesArrayTy &Sizes,
6613 MapFlagsArrayTy &Types) const {
6614 assert(!Cap->capturesVariableArrayType() &&
6615 "Not expecting to generate map info for a variable array type!");
6616
6617 BasePointers.clear();
6618 Pointers.clear();
6619 Sizes.clear();
6620 Types.clear();
6621
Samuel Antao6890b092016-07-28 14:25:09 +00006622 // We need to know when we generating information for the first component
6623 // associated with a capture, because the mapping flags depend on it.
6624 bool IsFirstComponentList = true;
6625
Samuel Antao86ace552016-04-27 22:40:57 +00006626 const ValueDecl *VD =
6627 Cap->capturesThis()
6628 ? nullptr
6629 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6630
Samuel Antao6890b092016-07-28 14:25:09 +00006631 // If this declaration appears in a is_device_ptr clause we just have to
6632 // pass the pointer by value. If it is a reference to a declaration, we just
6633 // pass its value, otherwise, if it is a member expression, we need to map
6634 // 'to' the field.
6635 if (!VD) {
6636 auto It = DevPointersMap.find(VD);
6637 if (It != DevPointersMap.end()) {
6638 for (auto L : It->second) {
6639 generateInfoForComponentList(
6640 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006641 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6642 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006643 IsFirstComponentList = false;
6644 }
6645 return;
6646 }
6647 } else if (DevPointersMap.count(VD)) {
6648 BasePointers.push_back({Arg, VD});
6649 Pointers.push_back(Arg);
6650 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6651 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6652 return;
6653 }
6654
Paul Robinson78fb1322016-08-01 22:12:46 +00006655 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006656 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006657 for (auto L : C->decl_component_lists(VD)) {
6658 assert(L.first == VD &&
6659 "We got information for the wrong declaration??");
6660 assert(!L.second.empty() &&
6661 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006662 generateInfoForComponentList(
6663 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6664 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006665 IsFirstComponentList = false;
6666 }
6667
6668 return;
6669 }
Samuel Antaod486f842016-05-26 16:53:38 +00006670
6671 /// \brief Generate the default map information for a given capture \a CI,
6672 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006673 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6674 const FieldDecl &RI, llvm::Value *CV,
6675 MapBaseValuesArrayTy &CurBasePointers,
6676 MapValuesArrayTy &CurPointers,
6677 MapValuesArrayTy &CurSizes,
6678 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006679
6680 // Do the default mapping.
6681 if (CI.capturesThis()) {
6682 CurBasePointers.push_back(CV);
6683 CurPointers.push_back(CV);
6684 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6685 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6686 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006687 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006688 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006689 CurBasePointers.push_back(CV);
6690 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006691 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006692 // We have to signal to the runtime captures passed by value that are
6693 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006694 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006695 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6696 } else {
6697 // Pointers are implicitly mapped with a zero size and no flags
6698 // (other than first map that is added for all implicit maps).
6699 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006700 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6701 }
6702 } else {
6703 assert(CI.capturesVariable() && "Expected captured reference.");
6704 CurBasePointers.push_back(CV);
6705 CurPointers.push_back(CV);
6706
6707 const ReferenceType *PtrTy =
6708 cast<ReferenceType>(RI.getType().getTypePtr());
6709 QualType ElementType = PtrTy->getPointeeType();
6710 CurSizes.push_back(CGF.getTypeSize(ElementType));
6711 // The default map type for a scalar/complex type is 'to' because by
6712 // default the value doesn't have to be retrieved. For an aggregate
6713 // type, the default is 'tofrom'.
6714 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006715 ? (OMP_MAP_TO | OMP_MAP_FROM)
6716 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006717
6718 // If we have a capture by reference we may need to add the private
6719 // pointer flag if the base declaration shows in some first-private
6720 // clause.
6721 CurMapTypes.back() =
6722 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6723 }
6724 // Every default map produces a single argument, so, it is always the
6725 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006726 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006727 }
Samuel Antao86ace552016-04-27 22:40:57 +00006728};
Samuel Antaodf158d52016-04-27 22:58:19 +00006729
6730enum OpenMPOffloadingReservedDeviceIDs {
6731 /// \brief Device ID if the device was not defined, runtime should get it
6732 /// from environment variables in the spec.
6733 OMP_DEVICEID_UNDEF = -1,
6734};
6735} // anonymous namespace
6736
6737/// \brief Emit the arrays used to pass the captures and map information to the
6738/// offloading runtime library. If there is no map or capture information,
6739/// return nullptr by reference.
6740static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006741emitOffloadingArrays(CodeGenFunction &CGF,
6742 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006743 MappableExprsHandler::MapValuesArrayTy &Pointers,
6744 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006745 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6746 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006747 auto &CGM = CGF.CGM;
6748 auto &Ctx = CGF.getContext();
6749
Samuel Antaocc10b852016-07-28 14:23:26 +00006750 // Reset the array information.
6751 Info.clearArrayInfo();
6752 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006753
Samuel Antaocc10b852016-07-28 14:23:26 +00006754 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006755 // Detect if we have any capture size requiring runtime evaluation of the
6756 // size so that a constant array could be eventually used.
6757 bool hasRuntimeEvaluationCaptureSize = false;
6758 for (auto *S : Sizes)
6759 if (!isa<llvm::Constant>(S)) {
6760 hasRuntimeEvaluationCaptureSize = true;
6761 break;
6762 }
6763
Samuel Antaocc10b852016-07-28 14:23:26 +00006764 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006765 QualType PointerArrayType =
6766 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6767 /*IndexTypeQuals=*/0);
6768
Samuel Antaocc10b852016-07-28 14:23:26 +00006769 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006770 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006771 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006772 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6773
6774 // If we don't have any VLA types or other types that require runtime
6775 // evaluation, we can use a constant array for the map sizes, otherwise we
6776 // need to fill up the arrays as we do for the pointers.
6777 if (hasRuntimeEvaluationCaptureSize) {
6778 QualType SizeArrayType = Ctx.getConstantArrayType(
6779 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6780 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006781 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006782 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6783 } else {
6784 // We expect all the sizes to be constant, so we collect them to create
6785 // a constant array.
6786 SmallVector<llvm::Constant *, 16> ConstSizes;
6787 for (auto S : Sizes)
6788 ConstSizes.push_back(cast<llvm::Constant>(S));
6789
6790 auto *SizesArrayInit = llvm::ConstantArray::get(
6791 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6792 auto *SizesArrayGbl = new llvm::GlobalVariable(
6793 CGM.getModule(), SizesArrayInit->getType(),
6794 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6795 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006796 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006797 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006798 }
6799
6800 // The map types are always constant so we don't need to generate code to
6801 // fill arrays. Instead, we create an array constant.
6802 llvm::Constant *MapTypesArrayInit =
6803 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6804 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6805 CGM.getModule(), MapTypesArrayInit->getType(),
6806 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6807 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006808 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006809 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006810
Samuel Antaocc10b852016-07-28 14:23:26 +00006811 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6812 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006813 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006814 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6815 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006816 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6817 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006818 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6819 CGF.Builder.CreateStore(BPVal, BPAddr);
6820
Samuel Antaocc10b852016-07-28 14:23:26 +00006821 if (Info.requiresDevicePointerInfo())
6822 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6823 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6824
Samuel Antaodf158d52016-04-27 22:58:19 +00006825 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006826 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006827 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6828 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006829 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6830 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006831 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6832 CGF.Builder.CreateStore(PVal, PAddr);
6833
6834 if (hasRuntimeEvaluationCaptureSize) {
6835 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006836 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6837 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006838 /*Idx0=*/0,
6839 /*Idx1=*/i);
6840 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6841 CGF.Builder.CreateStore(
6842 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6843 SAddr);
6844 }
6845 }
6846 }
6847}
6848/// \brief Emit the arguments to be passed to the runtime library based on the
6849/// arrays of pointers, sizes and map types.
6850static void emitOffloadingArraysArgument(
6851 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6852 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006853 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006854 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006855 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006856 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006857 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6858 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006859 /*Idx0=*/0, /*Idx1=*/0);
6860 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006861 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6862 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006863 /*Idx0=*/0,
6864 /*Idx1=*/0);
6865 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006866 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006867 /*Idx0=*/0, /*Idx1=*/0);
6868 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006869 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6870 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006871 /*Idx0=*/0,
6872 /*Idx1=*/0);
6873 } else {
6874 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6875 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6876 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6877 MapTypesArrayArg =
6878 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6879 }
Samuel Antao86ace552016-04-27 22:40:57 +00006880}
6881
Samuel Antaobed3c462015-10-02 16:14:20 +00006882void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6883 const OMPExecutableDirective &D,
6884 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006885 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006886 const Expr *IfCond, const Expr *Device,
6887 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006888 if (!CGF.HaveInsertPoint())
6889 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006890
Samuel Antaoee8fb302016-01-06 13:42:12 +00006891 assert(OutlinedFn && "Invalid outlined function!");
6892
Samuel Antao86ace552016-04-27 22:40:57 +00006893 // Fill up the arrays with all the captured variables.
6894 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006895 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006896 MappableExprsHandler::MapValuesArrayTy Pointers;
6897 MappableExprsHandler::MapValuesArrayTy Sizes;
6898 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006899
Samuel Antaocc10b852016-07-28 14:23:26 +00006900 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006901 MappableExprsHandler::MapValuesArrayTy CurPointers;
6902 MappableExprsHandler::MapValuesArrayTy CurSizes;
6903 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6904
Samuel Antaod486f842016-05-26 16:53:38 +00006905 // Get mappable expression information.
6906 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006907
6908 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6909 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006910 auto CV = CapturedVars.begin();
6911 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6912 CE = CS.capture_end();
6913 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00006914 CurBasePointers.clear();
6915 CurPointers.clear();
6916 CurSizes.clear();
6917 CurMapTypes.clear();
6918
6919 // VLA sizes are passed to the outlined region by copy and do not have map
6920 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006921 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006922 CurBasePointers.push_back(*CV);
6923 CurPointers.push_back(*CV);
6924 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006925 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006926 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6927 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006928 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006929 // If we have any information in the map clause, we use it, otherwise we
6930 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006931 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006932 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006933 if (CurBasePointers.empty())
6934 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6935 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006936 }
Samuel Antao86ace552016-04-27 22:40:57 +00006937 // We expect to have at least an element of information for this capture.
6938 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6939 assert(CurBasePointers.size() == CurPointers.size() &&
6940 CurBasePointers.size() == CurSizes.size() &&
6941 CurBasePointers.size() == CurMapTypes.size() &&
6942 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006943
Samuel Antao86ace552016-04-27 22:40:57 +00006944 // The kernel args are always the first elements of the base pointers
6945 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006946 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006947 // We need to append the results of this capture to what we already have.
6948 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6949 Pointers.append(CurPointers.begin(), CurPointers.end());
6950 Sizes.append(CurSizes.begin(), CurSizes.end());
6951 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006952 }
6953
Samuel Antaobed3c462015-10-02 16:14:20 +00006954 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00006955 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6956 OutlinedFn, OutlinedFnID, &D,
6957 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006958 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006959 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006960 TargetDataInfo Info;
6961 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6962 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6963 Info.PointersArray, Info.SizesArray,
6964 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006965
6966 // On top of the arrays that were filled up, the target offloading call
6967 // takes as arguments the device id as well as the host pointer. The host
6968 // pointer is used by the runtime library to identify the current target
6969 // region, so it only has to be unique and not necessarily point to
6970 // anything. It could be the pointer to the outlined function that
6971 // implements the target region, but we aren't using that so that the
6972 // compiler doesn't need to keep that, and could therefore inline the host
6973 // function if proven worthwhile during optimization.
6974
Samuel Antaoee8fb302016-01-06 13:42:12 +00006975 // From this point on, we need to have an ID of the target region defined.
6976 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006977
6978 // Emit device ID if any.
6979 llvm::Value *DeviceID;
6980 if (Device)
6981 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006982 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006983 else
6984 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6985
Samuel Antaodf158d52016-04-27 22:58:19 +00006986 // Emit the number of elements in the offloading arrays.
6987 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6988
Samuel Antaob68e2db2016-03-03 16:20:23 +00006989 // Return value of the runtime offloading call.
6990 llvm::Value *Return;
6991
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006992 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6993 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006994
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006995 // The target region is an outlined function launched by the runtime
6996 // via calls __tgt_target() or __tgt_target_teams().
6997 //
6998 // __tgt_target() launches a target region with one team and one thread,
6999 // executing a serial region. This master thread may in turn launch
7000 // more threads within its team upon encountering a parallel region,
7001 // however, no additional teams can be launched on the device.
7002 //
7003 // __tgt_target_teams() launches a target region with one or more teams,
7004 // each with one or more threads. This call is required for target
7005 // constructs such as:
7006 // 'target teams'
7007 // 'target' / 'teams'
7008 // 'target teams distribute parallel for'
7009 // 'target parallel'
7010 // and so on.
7011 //
7012 // Note that on the host and CPU targets, the runtime implementation of
7013 // these calls simply call the outlined function without forking threads.
7014 // The outlined functions themselves have runtime calls to
7015 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7016 // the compiler in emitTeamsCall() and emitParallelCall().
7017 //
7018 // In contrast, on the NVPTX target, the implementation of
7019 // __tgt_target_teams() launches a GPU kernel with the requested number
7020 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007021 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007022 // If we have NumTeams defined this means that we have an enclosed teams
7023 // region. Therefore we also expect to have NumThreads defined. These two
7024 // values should be defined in the presence of a teams directive,
7025 // regardless of having any clauses associated. If the user is using teams
7026 // but no clauses, these two values will be the default that should be
7027 // passed to the runtime library - a 32-bit integer with the value zero.
7028 assert(NumThreads && "Thread limit expression should be available along "
7029 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007030 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007031 DeviceID, OutlinedFnID,
7032 PointerNum, Info.BasePointersArray,
7033 Info.PointersArray, Info.SizesArray,
7034 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007035 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007036 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007037 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007038 } else {
7039 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007040 DeviceID, OutlinedFnID,
7041 PointerNum, Info.BasePointersArray,
7042 Info.PointersArray, Info.SizesArray,
7043 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007044 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007045 OffloadingArgs);
7046 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007047
Alexey Bataev2a007e02017-10-02 14:20:58 +00007048 // Check the error code and execute the host version if required.
7049 llvm::BasicBlock *OffloadFailedBlock =
7050 CGF.createBasicBlock("omp_offload.failed");
7051 llvm::BasicBlock *OffloadContBlock =
7052 CGF.createBasicBlock("omp_offload.cont");
7053 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7054 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7055
7056 CGF.EmitBlock(OffloadFailedBlock);
7057 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7058 CGF.EmitBranch(OffloadContBlock);
7059
7060 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007061 };
7062
Samuel Antaoee8fb302016-01-06 13:42:12 +00007063 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007064 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7065 PrePostActionTy &) {
7066 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7067 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007068 };
7069
7070 // If we have a target function ID it means that we need to support
7071 // offloading, otherwise, just execute on the host. We need to execute on host
7072 // regardless of the conditional in the if clause if, e.g., the user do not
7073 // specify target triples.
7074 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007075 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007076 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007077 else {
7078 RegionCodeGenTy ThenRCG(ThenGen);
7079 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007080 }
7081 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007082 RegionCodeGenTy ElseRCG(ElseGen);
7083 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007084 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007085}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007086
7087void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7088 StringRef ParentName) {
7089 if (!S)
7090 return;
7091
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007092 // Codegen OMP target directives that offload compute to the device.
7093 bool requiresDeviceCodegen =
7094 isa<OMPExecutableDirective>(S) &&
7095 isOpenMPTargetExecutionDirective(
7096 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007097
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007098 if (requiresDeviceCodegen) {
7099 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007100 unsigned DeviceID;
7101 unsigned FileID;
7102 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007103 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007104 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007105
7106 // Is this a target region that should not be emitted as an entry point? If
7107 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007108 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7109 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007110 return;
7111
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007112 switch (S->getStmtClass()) {
7113 case Stmt::OMPTargetDirectiveClass:
7114 CodeGenFunction::EmitOMPTargetDeviceFunction(
7115 CGM, ParentName, cast<OMPTargetDirective>(*S));
7116 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007117 case Stmt::OMPTargetParallelDirectiveClass:
7118 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7119 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7120 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007121 case Stmt::OMPTargetTeamsDirectiveClass:
7122 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7123 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7124 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007125 default:
7126 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7127 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007128 return;
7129 }
7130
7131 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007132 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007133 return;
7134
7135 scanForTargetRegionsFunctions(
7136 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7137 ParentName);
7138 return;
7139 }
7140
7141 // If this is a lambda function, look into its body.
7142 if (auto *L = dyn_cast<LambdaExpr>(S))
7143 S = L->getBody();
7144
7145 // Keep looking for target regions recursively.
7146 for (auto *II : S->children())
7147 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007148}
7149
7150bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7151 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7152
7153 // If emitting code for the host, we do not process FD here. Instead we do
7154 // the normal code generation.
7155 if (!CGM.getLangOpts().OpenMPIsDevice)
7156 return false;
7157
7158 // Try to detect target regions in the function.
7159 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7160
Samuel Antao4b75b872016-12-12 19:26:31 +00007161 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007162 // scanning. Therefore, we signal that this function is completely dealt
7163 // with.
7164 return true;
7165}
7166
7167bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7168 if (!CGM.getLangOpts().OpenMPIsDevice)
7169 return false;
7170
7171 // Check if there are Ctors/Dtors in this declaration and look for target
7172 // regions in it. We use the complete variant to produce the kernel name
7173 // mangling.
7174 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7175 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7176 for (auto *Ctor : RD->ctors()) {
7177 StringRef ParentName =
7178 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7179 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7180 }
7181 auto *Dtor = RD->getDestructor();
7182 if (Dtor) {
7183 StringRef ParentName =
7184 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7185 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7186 }
7187 }
7188
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007189 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007190 // implemented yet). Therefore we signal that GD was processed in this case.
7191 return true;
7192}
7193
7194bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7195 auto *VD = GD.getDecl();
7196 if (isa<FunctionDecl>(VD))
7197 return emitTargetFunctions(GD);
7198
7199 return emitTargetGlobalVariable(GD);
7200}
7201
7202llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7203 // If we have offloading in the current module, we need to emit the entries
7204 // now and register the offloading descriptor.
7205 createOffloadEntriesAndInfoMetadata();
7206
7207 // Create and register the offloading binary descriptors. This is the main
7208 // entity that captures all the information about offloading in the current
7209 // compilation unit.
7210 return createOffloadingBinaryDescriptorRegistration();
7211}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007212
7213void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7214 const OMPExecutableDirective &D,
7215 SourceLocation Loc,
7216 llvm::Value *OutlinedFn,
7217 ArrayRef<llvm::Value *> CapturedVars) {
7218 if (!CGF.HaveInsertPoint())
7219 return;
7220
7221 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7222 CodeGenFunction::RunCleanupsScope Scope(CGF);
7223
7224 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7225 llvm::Value *Args[] = {
7226 RTLoc,
7227 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7228 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7229 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7230 RealArgs.append(std::begin(Args), std::end(Args));
7231 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7232
7233 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7234 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7235}
7236
7237void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007238 const Expr *NumTeams,
7239 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007240 SourceLocation Loc) {
7241 if (!CGF.HaveInsertPoint())
7242 return;
7243
7244 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7245
Carlo Bertollic6872252016-04-04 15:55:02 +00007246 llvm::Value *NumTeamsVal =
7247 (NumTeams)
7248 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7249 CGF.CGM.Int32Ty, /* isSigned = */ true)
7250 : CGF.Builder.getInt32(0);
7251
7252 llvm::Value *ThreadLimitVal =
7253 (ThreadLimit)
7254 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7255 CGF.CGM.Int32Ty, /* isSigned = */ true)
7256 : CGF.Builder.getInt32(0);
7257
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007258 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007259 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7260 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007261 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7262 PushNumTeamsArgs);
7263}
Samuel Antaodf158d52016-04-27 22:58:19 +00007264
Samuel Antaocc10b852016-07-28 14:23:26 +00007265void CGOpenMPRuntime::emitTargetDataCalls(
7266 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7267 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007268 if (!CGF.HaveInsertPoint())
7269 return;
7270
Samuel Antaocc10b852016-07-28 14:23:26 +00007271 // Action used to replace the default codegen action and turn privatization
7272 // off.
7273 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007274
7275 // Generate the code for the opening of the data environment. Capture all the
7276 // arguments of the runtime call by reference because they are used in the
7277 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007278 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7279 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007280 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007281 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007282 MappableExprsHandler::MapValuesArrayTy Pointers;
7283 MappableExprsHandler::MapValuesArrayTy Sizes;
7284 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7285
7286 // Get map clause information.
7287 MappableExprsHandler MCHandler(D, CGF);
7288 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007289
7290 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007291 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007292
7293 llvm::Value *BasePointersArrayArg = nullptr;
7294 llvm::Value *PointersArrayArg = nullptr;
7295 llvm::Value *SizesArrayArg = nullptr;
7296 llvm::Value *MapTypesArrayArg = nullptr;
7297 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007298 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007299
7300 // Emit device ID if any.
7301 llvm::Value *DeviceID = nullptr;
7302 if (Device)
7303 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7304 CGF.Int32Ty, /*isSigned=*/true);
7305 else
7306 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7307
7308 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007309 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007310
7311 llvm::Value *OffloadingArgs[] = {
7312 DeviceID, PointerNum, BasePointersArrayArg,
7313 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7314 auto &RT = CGF.CGM.getOpenMPRuntime();
7315 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7316 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007317
7318 // If device pointer privatization is required, emit the body of the region
7319 // here. It will have to be duplicated: with and without privatization.
7320 if (!Info.CaptureDeviceAddrMap.empty())
7321 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007322 };
7323
7324 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007325 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007326 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007327
7328 llvm::Value *BasePointersArrayArg = nullptr;
7329 llvm::Value *PointersArrayArg = nullptr;
7330 llvm::Value *SizesArrayArg = nullptr;
7331 llvm::Value *MapTypesArrayArg = nullptr;
7332 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007333 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007334
7335 // Emit device ID if any.
7336 llvm::Value *DeviceID = nullptr;
7337 if (Device)
7338 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7339 CGF.Int32Ty, /*isSigned=*/true);
7340 else
7341 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7342
7343 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007344 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007345
7346 llvm::Value *OffloadingArgs[] = {
7347 DeviceID, PointerNum, BasePointersArrayArg,
7348 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7349 auto &RT = CGF.CGM.getOpenMPRuntime();
7350 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7351 OffloadingArgs);
7352 };
7353
Samuel Antaocc10b852016-07-28 14:23:26 +00007354 // If we need device pointer privatization, we need to emit the body of the
7355 // region with no privatization in the 'else' branch of the conditional.
7356 // Otherwise, we don't have to do anything.
7357 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7358 PrePostActionTy &) {
7359 if (!Info.CaptureDeviceAddrMap.empty()) {
7360 CodeGen.setAction(NoPrivAction);
7361 CodeGen(CGF);
7362 }
7363 };
7364
7365 // We don't have to do anything to close the region if the if clause evaluates
7366 // to false.
7367 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007368
7369 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007370 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007371 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007372 RegionCodeGenTy RCG(BeginThenGen);
7373 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007374 }
7375
Samuel Antaocc10b852016-07-28 14:23:26 +00007376 // If we don't require privatization of device pointers, we emit the body in
7377 // between the runtime calls. This avoids duplicating the body code.
7378 if (Info.CaptureDeviceAddrMap.empty()) {
7379 CodeGen.setAction(NoPrivAction);
7380 CodeGen(CGF);
7381 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007382
7383 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007384 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007385 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007386 RegionCodeGenTy RCG(EndThenGen);
7387 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007388 }
7389}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007390
Samuel Antao8d2d7302016-05-26 18:30:22 +00007391void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007392 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7393 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007394 if (!CGF.HaveInsertPoint())
7395 return;
7396
Samuel Antao8dd66282016-04-27 23:14:30 +00007397 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007398 isa<OMPTargetExitDataDirective>(D) ||
7399 isa<OMPTargetUpdateDirective>(D)) &&
7400 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007401
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007402 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007403 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007404 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007405 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007406 MappableExprsHandler::MapValuesArrayTy Pointers;
7407 MappableExprsHandler::MapValuesArrayTy Sizes;
7408 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7409
7410 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007411 MappableExprsHandler MEHandler(D, CGF);
7412 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007413
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007414 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007415 TargetDataInfo Info;
7416 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7417 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7418 Info.PointersArray, Info.SizesArray,
7419 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007420
7421 // Emit device ID if any.
7422 llvm::Value *DeviceID = nullptr;
7423 if (Device)
7424 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7425 CGF.Int32Ty, /*isSigned=*/true);
7426 else
7427 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7428
7429 // Emit the number of elements in the offloading arrays.
7430 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7431
7432 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007433 DeviceID, PointerNum, Info.BasePointersArray,
7434 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007435
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007436 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007437 // Select the right runtime function call for each expected standalone
7438 // directive.
7439 OpenMPRTLFunction RTLFn;
7440 switch (D.getDirectiveKind()) {
7441 default:
7442 llvm_unreachable("Unexpected standalone target data directive.");
7443 break;
7444 case OMPD_target_enter_data:
7445 RTLFn = OMPRTL__tgt_target_data_begin;
7446 break;
7447 case OMPD_target_exit_data:
7448 RTLFn = OMPRTL__tgt_target_data_end;
7449 break;
7450 case OMPD_target_update:
7451 RTLFn = OMPRTL__tgt_target_data_update;
7452 break;
7453 }
7454 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007455 };
7456
7457 // In the event we get an if clause, we don't have to take any action on the
7458 // else side.
7459 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7460
7461 if (IfCond) {
7462 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7463 } else {
7464 RegionCodeGenTy ThenGenRCG(ThenGen);
7465 ThenGenRCG(CGF);
7466 }
7467}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007468
7469namespace {
7470 /// Kind of parameter in a function with 'declare simd' directive.
7471 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7472 /// Attribute set of the parameter.
7473 struct ParamAttrTy {
7474 ParamKindTy Kind = Vector;
7475 llvm::APSInt StrideOrArg;
7476 llvm::APSInt Alignment;
7477 };
7478} // namespace
7479
7480static unsigned evaluateCDTSize(const FunctionDecl *FD,
7481 ArrayRef<ParamAttrTy> ParamAttrs) {
7482 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7483 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7484 // of that clause. The VLEN value must be power of 2.
7485 // In other case the notion of the function`s "characteristic data type" (CDT)
7486 // is used to compute the vector length.
7487 // CDT is defined in the following order:
7488 // a) For non-void function, the CDT is the return type.
7489 // b) If the function has any non-uniform, non-linear parameters, then the
7490 // CDT is the type of the first such parameter.
7491 // c) If the CDT determined by a) or b) above is struct, union, or class
7492 // type which is pass-by-value (except for the type that maps to the
7493 // built-in complex data type), the characteristic data type is int.
7494 // d) If none of the above three cases is applicable, the CDT is int.
7495 // The VLEN is then determined based on the CDT and the size of vector
7496 // register of that ISA for which current vector version is generated. The
7497 // VLEN is computed using the formula below:
7498 // VLEN = sizeof(vector_register) / sizeof(CDT),
7499 // where vector register size specified in section 3.2.1 Registers and the
7500 // Stack Frame of original AMD64 ABI document.
7501 QualType RetType = FD->getReturnType();
7502 if (RetType.isNull())
7503 return 0;
7504 ASTContext &C = FD->getASTContext();
7505 QualType CDT;
7506 if (!RetType.isNull() && !RetType->isVoidType())
7507 CDT = RetType;
7508 else {
7509 unsigned Offset = 0;
7510 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7511 if (ParamAttrs[Offset].Kind == Vector)
7512 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7513 ++Offset;
7514 }
7515 if (CDT.isNull()) {
7516 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7517 if (ParamAttrs[I + Offset].Kind == Vector) {
7518 CDT = FD->getParamDecl(I)->getType();
7519 break;
7520 }
7521 }
7522 }
7523 }
7524 if (CDT.isNull())
7525 CDT = C.IntTy;
7526 CDT = CDT->getCanonicalTypeUnqualified();
7527 if (CDT->isRecordType() || CDT->isUnionType())
7528 CDT = C.IntTy;
7529 return C.getTypeSize(CDT);
7530}
7531
7532static void
7533emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007534 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007535 ArrayRef<ParamAttrTy> ParamAttrs,
7536 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7537 struct ISADataTy {
7538 char ISA;
7539 unsigned VecRegSize;
7540 };
7541 ISADataTy ISAData[] = {
7542 {
7543 'b', 128
7544 }, // SSE
7545 {
7546 'c', 256
7547 }, // AVX
7548 {
7549 'd', 256
7550 }, // AVX2
7551 {
7552 'e', 512
7553 }, // AVX512
7554 };
7555 llvm::SmallVector<char, 2> Masked;
7556 switch (State) {
7557 case OMPDeclareSimdDeclAttr::BS_Undefined:
7558 Masked.push_back('N');
7559 Masked.push_back('M');
7560 break;
7561 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7562 Masked.push_back('N');
7563 break;
7564 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7565 Masked.push_back('M');
7566 break;
7567 }
7568 for (auto Mask : Masked) {
7569 for (auto &Data : ISAData) {
7570 SmallString<256> Buffer;
7571 llvm::raw_svector_ostream Out(Buffer);
7572 Out << "_ZGV" << Data.ISA << Mask;
7573 if (!VLENVal) {
7574 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7575 evaluateCDTSize(FD, ParamAttrs));
7576 } else
7577 Out << VLENVal;
7578 for (auto &ParamAttr : ParamAttrs) {
7579 switch (ParamAttr.Kind){
7580 case LinearWithVarStride:
7581 Out << 's' << ParamAttr.StrideOrArg;
7582 break;
7583 case Linear:
7584 Out << 'l';
7585 if (!!ParamAttr.StrideOrArg)
7586 Out << ParamAttr.StrideOrArg;
7587 break;
7588 case Uniform:
7589 Out << 'u';
7590 break;
7591 case Vector:
7592 Out << 'v';
7593 break;
7594 }
7595 if (!!ParamAttr.Alignment)
7596 Out << 'a' << ParamAttr.Alignment;
7597 }
7598 Out << '_' << Fn->getName();
7599 Fn->addFnAttr(Out.str());
7600 }
7601 }
7602}
7603
7604void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7605 llvm::Function *Fn) {
7606 ASTContext &C = CGM.getContext();
7607 FD = FD->getCanonicalDecl();
7608 // Map params to their positions in function decl.
7609 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7610 if (isa<CXXMethodDecl>(FD))
7611 ParamPositions.insert({FD, 0});
7612 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007613 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007614 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7615 ++ParamPos;
7616 }
7617 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7618 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7619 // Mark uniform parameters.
7620 for (auto *E : Attr->uniforms()) {
7621 E = E->IgnoreParenImpCasts();
7622 unsigned Pos;
7623 if (isa<CXXThisExpr>(E))
7624 Pos = ParamPositions[FD];
7625 else {
7626 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7627 ->getCanonicalDecl();
7628 Pos = ParamPositions[PVD];
7629 }
7630 ParamAttrs[Pos].Kind = Uniform;
7631 }
7632 // Get alignment info.
7633 auto NI = Attr->alignments_begin();
7634 for (auto *E : Attr->aligneds()) {
7635 E = E->IgnoreParenImpCasts();
7636 unsigned Pos;
7637 QualType ParmTy;
7638 if (isa<CXXThisExpr>(E)) {
7639 Pos = ParamPositions[FD];
7640 ParmTy = E->getType();
7641 } else {
7642 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7643 ->getCanonicalDecl();
7644 Pos = ParamPositions[PVD];
7645 ParmTy = PVD->getType();
7646 }
7647 ParamAttrs[Pos].Alignment =
7648 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7649 : llvm::APSInt::getUnsigned(
7650 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7651 .getQuantity());
7652 ++NI;
7653 }
7654 // Mark linear parameters.
7655 auto SI = Attr->steps_begin();
7656 auto MI = Attr->modifiers_begin();
7657 for (auto *E : Attr->linears()) {
7658 E = E->IgnoreParenImpCasts();
7659 unsigned Pos;
7660 if (isa<CXXThisExpr>(E))
7661 Pos = ParamPositions[FD];
7662 else {
7663 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7664 ->getCanonicalDecl();
7665 Pos = ParamPositions[PVD];
7666 }
7667 auto &ParamAttr = ParamAttrs[Pos];
7668 ParamAttr.Kind = Linear;
7669 if (*SI) {
7670 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7671 Expr::SE_AllowSideEffects)) {
7672 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7673 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7674 ParamAttr.Kind = LinearWithVarStride;
7675 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7676 ParamPositions[StridePVD->getCanonicalDecl()]);
7677 }
7678 }
7679 }
7680 }
7681 ++SI;
7682 ++MI;
7683 }
7684 llvm::APSInt VLENVal;
7685 if (const Expr *VLEN = Attr->getSimdlen())
7686 VLENVal = VLEN->EvaluateKnownConstInt(C);
7687 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7688 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7689 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7690 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7691 }
7692}
Alexey Bataev8b427062016-05-25 12:36:08 +00007693
7694namespace {
7695/// Cleanup action for doacross support.
7696class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7697public:
7698 static const int DoacrossFinArgs = 2;
7699
7700private:
7701 llvm::Value *RTLFn;
7702 llvm::Value *Args[DoacrossFinArgs];
7703
7704public:
7705 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7706 : RTLFn(RTLFn) {
7707 assert(CallArgs.size() == DoacrossFinArgs);
7708 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7709 }
7710 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7711 if (!CGF.HaveInsertPoint())
7712 return;
7713 CGF.EmitRuntimeCall(RTLFn, Args);
7714 }
7715};
7716} // namespace
7717
7718void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7719 const OMPLoopDirective &D) {
7720 if (!CGF.HaveInsertPoint())
7721 return;
7722
7723 ASTContext &C = CGM.getContext();
7724 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7725 RecordDecl *RD;
7726 if (KmpDimTy.isNull()) {
7727 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7728 // kmp_int64 lo; // lower
7729 // kmp_int64 up; // upper
7730 // kmp_int64 st; // stride
7731 // };
7732 RD = C.buildImplicitRecord("kmp_dim");
7733 RD->startDefinition();
7734 addFieldToRecordDecl(C, RD, Int64Ty);
7735 addFieldToRecordDecl(C, RD, Int64Ty);
7736 addFieldToRecordDecl(C, RD, Int64Ty);
7737 RD->completeDefinition();
7738 KmpDimTy = C.getRecordType(RD);
7739 } else
7740 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7741
7742 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7743 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7744 enum { LowerFD = 0, UpperFD, StrideFD };
7745 // Fill dims with data.
7746 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7747 // dims.upper = num_iterations;
7748 LValue UpperLVal =
7749 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7750 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7751 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7752 Int64Ty, D.getNumIterations()->getExprLoc());
7753 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7754 // dims.stride = 1;
7755 LValue StrideLVal =
7756 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7757 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7758 StrideLVal);
7759
7760 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7761 // kmp_int32 num_dims, struct kmp_dim * dims);
7762 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7763 getThreadID(CGF, D.getLocStart()),
7764 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7765 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7766 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7767
7768 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7769 CGF.EmitRuntimeCall(RTLFn, Args);
7770 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7771 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7772 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7773 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7774 llvm::makeArrayRef(FiniArgs));
7775}
7776
7777void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7778 const OMPDependClause *C) {
7779 QualType Int64Ty =
7780 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7781 const Expr *CounterVal = C->getCounterValue();
7782 assert(CounterVal);
7783 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7784 CounterVal->getType(), Int64Ty,
7785 CounterVal->getExprLoc());
7786 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7787 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7788 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7789 getThreadID(CGF, C->getLocStart()),
7790 CntAddr.getPointer()};
7791 llvm::Value *RTLFn;
7792 if (C->getDependencyKind() == OMPC_DEPEND_source)
7793 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7794 else {
7795 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7796 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7797 }
7798 CGF.EmitRuntimeCall(RTLFn, Args);
7799}
7800
Alexey Bataev3c595a62017-08-14 15:01:03 +00007801void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7802 ArrayRef<llvm::Value *> Args,
7803 SourceLocation Loc) const {
7804 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7805
7806 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007807 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007808 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007809 return;
7810 }
7811 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007812 CGF.EmitRuntimeCall(Callee, Args);
7813}
7814
7815void CGOpenMPRuntime::emitOutlinedFunctionCall(
7816 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7817 ArrayRef<llvm::Value *> Args) const {
7818 assert(Loc.isValid() && "Outlined function call location must be valid.");
7819 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007820}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007821
7822Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7823 const VarDecl *NativeParam,
7824 const VarDecl *TargetParam) const {
7825 return CGF.GetAddrOfLocalVar(NativeParam);
7826}