blob: 3ca92531b9c3198134bd4f9d4101b7be4bfc56fc [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,
789 QualType Type, const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000790 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000791 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000792 // Perform element-by-element initialization.
793 QualType ElementTy;
794
795 // Drill down to the base element type on both arrays.
796 auto ArrayTy = Type->getAsArrayTypeUnsafe();
797 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
798 DestAddr =
799 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
800 if (DRD)
801 SrcAddr =
802 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
803
804 llvm::Value *SrcBegin = nullptr;
805 if (DRD)
806 SrcBegin = SrcAddr.getPointer();
807 auto DestBegin = DestAddr.getPointer();
808 // Cast from pointer to array type to pointer to single element.
809 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
810 // The basic structure here is a while-do loop.
811 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
812 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
813 auto IsEmpty =
814 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
815 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
816
817 // Enter the loop body, making that address the current address.
818 auto EntryBB = CGF.Builder.GetInsertBlock();
819 CGF.EmitBlock(BodyBB);
820
821 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
822
823 llvm::PHINode *SrcElementPHI = nullptr;
824 Address SrcElementCurrent = Address::invalid();
825 if (DRD) {
826 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
827 "omp.arraycpy.srcElementPast");
828 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
829 SrcElementCurrent =
830 Address(SrcElementPHI,
831 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
832 }
833 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
834 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
835 DestElementPHI->addIncoming(DestBegin, EntryBB);
836 Address DestElementCurrent =
837 Address(DestElementPHI,
838 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
839
840 // Emit copy.
841 {
842 CodeGenFunction::RunCleanupsScope InitScope(CGF);
843 if (DRD && (DRD->getInitializer() || !Init)) {
844 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
845 SrcElementCurrent, ElementTy);
846 } else
847 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
848 /*IsInitializer=*/false);
849 }
850
851 if (DRD) {
852 // Shift the address forward by one element.
853 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
854 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
855 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
856 }
857
858 // Shift the address forward by one element.
859 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
860 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
861 // Check whether we've reached the end.
862 auto Done =
863 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
864 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
865 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
866
867 // Done.
868 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
869}
870
871LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000872 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000873}
874
875LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
876 const Expr *E) {
877 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
878 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
879 return LValue();
880}
881
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000882void ReductionCodeGen::emitAggregateInitialization(
883 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
884 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000885 // Emit VarDecl with copy init for arrays.
886 // Get the address of the original variable captured in current
887 // captured region.
888 auto *PrivateVD =
889 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000890 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
891 DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000892 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000893}
894
895ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
896 ArrayRef<const Expr *> Privates,
897 ArrayRef<const Expr *> ReductionOps) {
898 ClausesData.reserve(Shareds.size());
899 SharedAddresses.reserve(Shareds.size());
900 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000901 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000902 auto IPriv = Privates.begin();
903 auto IRed = ReductionOps.begin();
904 for (const auto *Ref : Shareds) {
905 ClausesData.emplace_back(Ref, *IPriv, *IRed);
906 std::advance(IPriv, 1);
907 std::advance(IRed, 1);
908 }
909}
910
911void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
912 assert(SharedAddresses.size() == N &&
913 "Number of generated lvalues must be exactly N.");
914 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
915 emitSharedLValueUB(CGF, ClausesData[N].Ref));
916}
917
918void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
919 auto *PrivateVD =
920 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
921 QualType PrivateType = PrivateVD->getType();
922 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
923 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000924 Sizes.emplace_back(
925 CGF.getTypeSize(
926 SharedAddresses[N].first.getType().getNonReferenceType()),
927 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000928 return;
929 }
930 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000931 llvm::Value *SizeInChars;
932 llvm::Type *ElemType =
933 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
934 ->getElementType();
935 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000936 if (AsArraySection) {
937 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
938 SharedAddresses[N].first.getPointer());
939 Size = CGF.Builder.CreateNUWAdd(
940 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000941 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000943 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000944 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000945 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000946 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 CodeGenFunction::OpaqueValueMapping OpaqueMap(
949 CGF,
950 cast<OpaqueValueExpr>(
951 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
952 RValue::get(Size));
953 CGF.EmitVariablyModifiedType(PrivateType);
954}
955
956void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
957 llvm::Value *Size) {
958 auto *PrivateVD =
959 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
960 QualType PrivateType = PrivateVD->getType();
961 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
962 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000963 assert(!Size && !Sizes[N].second &&
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000964 "Size should be nullptr for non-variably modified redution "
965 "items.");
966 return;
967 }
968 CodeGenFunction::OpaqueValueMapping OpaqueMap(
969 CGF,
970 cast<OpaqueValueExpr>(
971 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
972 RValue::get(Size));
973 CGF.EmitVariablyModifiedType(PrivateType);
974}
975
976void ReductionCodeGen::emitInitialization(
977 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
978 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
979 assert(SharedAddresses.size() > N && "No variable was generated");
980 auto *PrivateVD =
981 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
982 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
983 QualType PrivateType = PrivateVD->getType();
984 PrivateAddr = CGF.Builder.CreateElementBitCast(
985 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
986 QualType SharedType = SharedAddresses[N].first.getType();
987 SharedLVal = CGF.MakeAddrLValue(
988 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
989 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +0000990 SharedType, SharedAddresses[N].first.getBaseInfo(),
991 CGF.CGM.getTBAAAccessInfo(SharedType));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000992 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
993 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000994 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000995 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
996 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
997 PrivateAddr, SharedLVal.getAddress(),
998 SharedLVal.getType());
999 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1000 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1001 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1002 PrivateVD->getType().getQualifiers(),
1003 /*IsInitializer=*/false);
1004 }
1005}
1006
1007bool ReductionCodeGen::needCleanups(unsigned N) {
1008 auto *PrivateVD =
1009 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1010 QualType PrivateType = PrivateVD->getType();
1011 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1012 return DTorKind != QualType::DK_none;
1013}
1014
1015void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1016 Address PrivateAddr) {
1017 auto *PrivateVD =
1018 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1019 QualType PrivateType = PrivateVD->getType();
1020 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1021 if (needCleanups(N)) {
1022 PrivateAddr = CGF.Builder.CreateElementBitCast(
1023 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1024 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1025 }
1026}
1027
1028static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1029 LValue BaseLV) {
1030 BaseTy = BaseTy.getNonReferenceType();
1031 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1032 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1033 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1034 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1035 else {
1036 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1037 BaseTy->castAs<ReferenceType>());
1038 }
1039 BaseTy = BaseTy->getPointeeType();
1040 }
1041 return CGF.MakeAddrLValue(
1042 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1043 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001044 BaseLV.getType(), BaseLV.getBaseInfo(),
1045 CGF.CGM.getTBAAAccessInfo(BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001046}
1047
1048static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1049 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1050 llvm::Value *Addr) {
1051 Address Tmp = Address::invalid();
1052 Address TopTmp = Address::invalid();
1053 Address MostTopTmp = Address::invalid();
1054 BaseTy = BaseTy.getNonReferenceType();
1055 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1056 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1057 Tmp = CGF.CreateMemTemp(BaseTy);
1058 if (TopTmp.isValid())
1059 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1060 else
1061 MostTopTmp = Tmp;
1062 TopTmp = Tmp;
1063 BaseTy = BaseTy->getPointeeType();
1064 }
1065 llvm::Type *Ty = BaseLVType;
1066 if (Tmp.isValid())
1067 Ty = Tmp.getElementType();
1068 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1069 if (Tmp.isValid()) {
1070 CGF.Builder.CreateStore(Addr, Tmp);
1071 return MostTopTmp;
1072 }
1073 return Address(Addr, BaseLVAlignment);
1074}
1075
1076Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1077 Address PrivateAddr) {
1078 const DeclRefExpr *DE;
1079 const VarDecl *OrigVD = nullptr;
1080 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1081 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1082 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1083 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1084 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1085 Base = TempASE->getBase()->IgnoreParenImpCasts();
1086 DE = cast<DeclRefExpr>(Base);
1087 OrigVD = cast<VarDecl>(DE->getDecl());
1088 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1089 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1090 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1091 Base = TempASE->getBase()->IgnoreParenImpCasts();
1092 DE = cast<DeclRefExpr>(Base);
1093 OrigVD = cast<VarDecl>(DE->getDecl());
1094 }
1095 if (OrigVD) {
1096 BaseDecls.emplace_back(OrigVD);
1097 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1098 LValue BaseLValue =
1099 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1100 OriginalBaseLValue);
1101 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1102 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1103 llvm::Value *Ptr =
1104 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1105 return castToBase(CGF, OrigVD->getType(),
1106 SharedAddresses[N].first.getType(),
1107 OriginalBaseLValue.getPointer()->getType(),
1108 OriginalBaseLValue.getAlignment(), Ptr);
1109 }
1110 BaseDecls.emplace_back(
1111 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1112 return PrivateAddr;
1113}
1114
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001115bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1116 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1117 return DRD && DRD->getInitializer();
1118}
1119
Alexey Bataev18095712014-10-10 12:19:54 +00001120LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001121 return CGF.EmitLoadOfPointerLValue(
1122 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1123 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001124}
1125
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001126void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001127 if (!CGF.HaveInsertPoint())
1128 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001129 // 1.2.2 OpenMP Language Terminology
1130 // Structured block - An executable statement with a single entry at the
1131 // top and a single exit at the bottom.
1132 // The point of exit cannot be a branch out of the structured block.
1133 // longjmp() and throw() must not violate the entry/exit criteria.
1134 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001135 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001136 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001137}
1138
Alexey Bataev62b63b12015-03-10 07:28:44 +00001139LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1140 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001141 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1142 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001143 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001144}
1145
Alexey Bataev9959db52014-05-06 10:08:46 +00001146CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001147 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001148 IdentTy = llvm::StructType::create(
1149 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1150 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001151 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001152 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001153
1154 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001155}
1156
Alexey Bataev91797552015-03-18 04:13:55 +00001157void CGOpenMPRuntime::clear() {
1158 InternalVars.clear();
1159}
1160
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001161static llvm::Function *
1162emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1163 const Expr *CombinerInitializer, const VarDecl *In,
1164 const VarDecl *Out, bool IsCombiner) {
1165 // void .omp_combiner.(Ty *in, Ty *out);
1166 auto &C = CGM.getContext();
1167 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1168 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001169 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001170 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001171 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001172 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001173 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001174 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001175 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001176 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001177 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1178 auto *Fn = llvm::Function::Create(
1179 FnTy, llvm::GlobalValue::InternalLinkage,
1180 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1181 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001182 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001183 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001184 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001185 CodeGenFunction CGF(CGM);
1186 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1187 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1188 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1189 CodeGenFunction::OMPPrivateScope Scope(CGF);
1190 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1191 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1192 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1193 .getAddress();
1194 });
1195 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1196 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1197 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1198 .getAddress();
1199 });
1200 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001201 if (!IsCombiner && Out->hasInit() &&
1202 !CGF.isTrivialInitializer(Out->getInit())) {
1203 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1204 Out->getType().getQualifiers(),
1205 /*IsInitializer=*/true);
1206 }
1207 if (CombinerInitializer)
1208 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001209 Scope.ForceCleanup();
1210 CGF.FinishFunction();
1211 return Fn;
1212}
1213
1214void CGOpenMPRuntime::emitUserDefinedReduction(
1215 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1216 if (UDRMap.count(D) > 0)
1217 return;
1218 auto &C = CGM.getContext();
1219 if (!In || !Out) {
1220 In = &C.Idents.get("omp_in");
1221 Out = &C.Idents.get("omp_out");
1222 }
1223 llvm::Function *Combiner = emitCombinerOrInitializer(
1224 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1225 cast<VarDecl>(D->lookup(Out).front()),
1226 /*IsCombiner=*/true);
1227 llvm::Function *Initializer = nullptr;
1228 if (auto *Init = D->getInitializer()) {
1229 if (!Priv || !Orig) {
1230 Priv = &C.Idents.get("omp_priv");
1231 Orig = &C.Idents.get("omp_orig");
1232 }
1233 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001234 CGM, D->getType(),
1235 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1236 : nullptr,
1237 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001238 cast<VarDecl>(D->lookup(Priv).front()),
1239 /*IsCombiner=*/false);
1240 }
1241 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1242 if (CGF) {
1243 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1244 Decls.second.push_back(D);
1245 }
1246}
1247
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001248std::pair<llvm::Function *, llvm::Function *>
1249CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1250 auto I = UDRMap.find(D);
1251 if (I != UDRMap.end())
1252 return I->second;
1253 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1254 return UDRMap.lookup(D);
1255}
1256
John McCall7f416cc2015-09-08 08:05:57 +00001257// Layout information for ident_t.
1258static CharUnits getIdentAlign(CodeGenModule &CGM) {
1259 return CGM.getPointerAlign();
1260}
1261static CharUnits getIdentSize(CodeGenModule &CGM) {
1262 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1263 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1264}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001265static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001266 // All the fields except the last are i32, so this works beautifully.
1267 return unsigned(Field) * CharUnits::fromQuantity(4);
1268}
1269static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001270 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001271 const llvm::Twine &Name = "") {
1272 auto Offset = getOffsetOfIdentField(Field);
1273 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1274}
1275
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001276static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1277 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1278 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1279 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001280 assert(ThreadIDVar->getType()->isPointerType() &&
1281 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001282 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001283 bool HasCancel = false;
1284 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1285 HasCancel = OPD->hasCancel();
1286 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1287 HasCancel = OPSD->hasCancel();
1288 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1289 HasCancel = OPFD->hasCancel();
1290 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001291 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001292 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001293 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001294}
1295
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001296llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1297 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1298 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1299 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1300 return emitParallelOrTeamsOutlinedFunction(
1301 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1302}
1303
1304llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1305 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1306 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1307 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1308 return emitParallelOrTeamsOutlinedFunction(
1309 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1310}
1311
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001312llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1313 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001314 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1315 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1316 bool Tied, unsigned &NumberOfParts) {
1317 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1318 PrePostActionTy &) {
1319 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1320 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1321 llvm::Value *TaskArgs[] = {
1322 UpLoc, ThreadID,
1323 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1324 TaskTVar->getType()->castAs<PointerType>())
1325 .getPointer()};
1326 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1327 };
1328 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1329 UntiedCodeGen);
1330 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001331 assert(!ThreadIDVar->getType()->isPointerType() &&
1332 "thread id variable must be of type kmp_int32 for tasks");
1333 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001334 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001335 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001336 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1337 InnermostKind,
1338 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001339 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001340 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1341 if (!Tied)
1342 NumberOfParts = Action.getNumberOfParts();
1343 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001344}
1345
Alexey Bataev50b3c952016-02-19 10:38:26 +00001346Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001347 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001348 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001349 if (!Entry) {
1350 if (!DefaultOpenMPPSource) {
1351 // Initialize default location for psource field of ident_t structure of
1352 // all ident_t objects. Format is ";file;function;line;column;;".
1353 // Taken from
1354 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1355 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001356 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001357 DefaultOpenMPPSource =
1358 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1359 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001360
John McCall23c9dc62016-11-28 22:18:27 +00001361 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001362 auto fields = builder.beginStruct(IdentTy);
1363 fields.addInt(CGM.Int32Ty, 0);
1364 fields.addInt(CGM.Int32Ty, Flags);
1365 fields.addInt(CGM.Int32Ty, 0);
1366 fields.addInt(CGM.Int32Ty, 0);
1367 fields.add(DefaultOpenMPPSource);
1368 auto DefaultOpenMPLocation =
1369 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1370 llvm::GlobalValue::PrivateLinkage);
1371 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1372
John McCall7f416cc2015-09-08 08:05:57 +00001373 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001374 }
John McCall7f416cc2015-09-08 08:05:57 +00001375 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001376}
1377
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001378llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1379 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001380 unsigned Flags) {
1381 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001382 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001383 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001384 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001385 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001386
1387 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1388
John McCall7f416cc2015-09-08 08:05:57 +00001389 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001390 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1391 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001392 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1393
Alexander Musmanc6388682014-12-15 07:07:06 +00001394 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1395 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001396 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001397 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001398 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1399 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001400 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001401 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001402 LocValue = AI;
1403
1404 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1405 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001406 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001407 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001408 }
1409
1410 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001411 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001412
Alexey Bataevf002aca2014-05-30 05:48:40 +00001413 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1414 if (OMPDebugLoc == nullptr) {
1415 SmallString<128> Buffer2;
1416 llvm::raw_svector_ostream OS2(Buffer2);
1417 // Build debug location
1418 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1419 OS2 << ";" << PLoc.getFilename() << ";";
1420 if (const FunctionDecl *FD =
1421 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1422 OS2 << FD->getQualifiedNameAsString();
1423 }
1424 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1425 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1426 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001427 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001428 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001429 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1430
John McCall7f416cc2015-09-08 08:05:57 +00001431 // Our callers always pass this to a runtime function, so for
1432 // convenience, go ahead and return a naked pointer.
1433 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001434}
1435
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001436llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1437 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001438 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1439
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001440 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001441 // Check whether we've already cached a load of the thread id in this
1442 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001443 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001444 if (I != OpenMPLocThreadIDMap.end()) {
1445 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001446 if (ThreadID != nullptr)
1447 return ThreadID;
1448 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001449 // If exceptions are enabled, do not use parameter to avoid possible crash.
1450 if (!CGF.getInvokeDest()) {
1451 if (auto *OMPRegionInfo =
1452 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1453 if (OMPRegionInfo->getThreadIDVariable()) {
1454 // Check if this an outlined function with thread id passed as argument.
1455 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1456 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1457 // If value loaded in entry block, cache it and use it everywhere in
1458 // function.
1459 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1460 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1461 Elem.second.ThreadID = ThreadID;
1462 }
1463 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001464 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001465 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001466 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001467
1468 // This is not an outlined function region - need to call __kmpc_int32
1469 // kmpc_global_thread_num(ident_t *loc).
1470 // Generate thread id value and cache this value for use across the
1471 // function.
1472 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1473 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1474 ThreadID =
1475 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1476 emitUpdateLocation(CGF, Loc));
1477 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1478 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001479 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001480}
1481
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001482void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001483 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001484 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1485 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001486 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1487 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1488 UDRMap.erase(D);
1489 }
1490 FunctionUDRMap.erase(CGF.CurFn);
1491 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001492}
1493
1494llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001495 if (!IdentTy) {
1496 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001497 return llvm::PointerType::getUnqual(IdentTy);
1498}
1499
1500llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001501 if (!Kmpc_MicroTy) {
1502 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1503 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1504 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1505 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1506 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001507 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1508}
1509
1510llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001511CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001512 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001513 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001514 case OMPRTL__kmpc_fork_call: {
1515 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1516 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001517 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1518 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001519 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001520 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1522 break;
1523 }
1524 case OMPRTL__kmpc_global_thread_num: {
1525 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001526 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001527 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001528 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001529 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1530 break;
1531 }
Alexey Bataev97720002014-11-11 04:05:39 +00001532 case OMPRTL__kmpc_threadprivate_cached: {
1533 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1534 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1535 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1536 CGM.VoidPtrTy, CGM.SizeTy,
1537 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1538 llvm::FunctionType *FnTy =
1539 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1540 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1541 break;
1542 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001543 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001544 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1545 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001546 llvm::Type *TypeParams[] = {
1547 getIdentTyPointerTy(), CGM.Int32Ty,
1548 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1549 llvm::FunctionType *FnTy =
1550 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1552 break;
1553 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001554 case OMPRTL__kmpc_critical_with_hint: {
1555 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1556 // kmp_critical_name *crit, uintptr_t hint);
1557 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1558 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1559 CGM.IntPtrTy};
1560 llvm::FunctionType *FnTy =
1561 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1562 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1563 break;
1564 }
Alexey Bataev97720002014-11-11 04:05:39 +00001565 case OMPRTL__kmpc_threadprivate_register: {
1566 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1567 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1568 // typedef void *(*kmpc_ctor)(void *);
1569 auto KmpcCtorTy =
1570 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1571 /*isVarArg*/ false)->getPointerTo();
1572 // typedef void *(*kmpc_cctor)(void *, void *);
1573 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1574 auto KmpcCopyCtorTy =
1575 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1576 /*isVarArg*/ false)->getPointerTo();
1577 // typedef void (*kmpc_dtor)(void *);
1578 auto KmpcDtorTy =
1579 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1580 ->getPointerTo();
1581 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1582 KmpcCopyCtorTy, KmpcDtorTy};
1583 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1584 /*isVarArg*/ false);
1585 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1586 break;
1587 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001588 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001589 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1590 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001591 llvm::Type *TypeParams[] = {
1592 getIdentTyPointerTy(), CGM.Int32Ty,
1593 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1594 llvm::FunctionType *FnTy =
1595 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1596 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1597 break;
1598 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001599 case OMPRTL__kmpc_cancel_barrier: {
1600 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1601 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001602 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1603 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001604 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1605 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001606 break;
1607 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001608 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001609 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001610 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1611 llvm::FunctionType *FnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1613 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1614 break;
1615 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001616 case OMPRTL__kmpc_for_static_fini: {
1617 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1618 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1619 llvm::FunctionType *FnTy =
1620 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1621 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1622 break;
1623 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001624 case OMPRTL__kmpc_push_num_threads: {
1625 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1626 // kmp_int32 num_threads)
1627 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1628 CGM.Int32Ty};
1629 llvm::FunctionType *FnTy =
1630 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1631 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1632 break;
1633 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001634 case OMPRTL__kmpc_serialized_parallel: {
1635 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1636 // global_tid);
1637 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1638 llvm::FunctionType *FnTy =
1639 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1641 break;
1642 }
1643 case OMPRTL__kmpc_end_serialized_parallel: {
1644 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1645 // global_tid);
1646 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1647 llvm::FunctionType *FnTy =
1648 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1649 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1650 break;
1651 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001652 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001653 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001654 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1655 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001657 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1658 break;
1659 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001660 case OMPRTL__kmpc_master: {
1661 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1662 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1663 llvm::FunctionType *FnTy =
1664 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1665 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1666 break;
1667 }
1668 case OMPRTL__kmpc_end_master: {
1669 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1670 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1671 llvm::FunctionType *FnTy =
1672 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1673 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1674 break;
1675 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001676 case OMPRTL__kmpc_omp_taskyield: {
1677 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1678 // int end_part);
1679 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1680 llvm::FunctionType *FnTy =
1681 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1682 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1683 break;
1684 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001685 case OMPRTL__kmpc_single: {
1686 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1687 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1688 llvm::FunctionType *FnTy =
1689 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1690 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1691 break;
1692 }
1693 case OMPRTL__kmpc_end_single: {
1694 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1695 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1696 llvm::FunctionType *FnTy =
1697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1698 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1699 break;
1700 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001701 case OMPRTL__kmpc_omp_task_alloc: {
1702 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1703 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1704 // kmp_routine_entry_t *task_entry);
1705 assert(KmpRoutineEntryPtrTy != nullptr &&
1706 "Type kmp_routine_entry_t must be created.");
1707 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1708 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1709 // Return void * and then cast to particular kmp_task_t type.
1710 llvm::FunctionType *FnTy =
1711 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1712 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1713 break;
1714 }
1715 case OMPRTL__kmpc_omp_task: {
1716 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1717 // *new_task);
1718 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1719 CGM.VoidPtrTy};
1720 llvm::FunctionType *FnTy =
1721 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1722 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1723 break;
1724 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001725 case OMPRTL__kmpc_copyprivate: {
1726 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001727 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001728 // kmp_int32 didit);
1729 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1730 auto *CpyFnTy =
1731 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001732 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001733 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1734 CGM.Int32Ty};
1735 llvm::FunctionType *FnTy =
1736 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1737 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1738 break;
1739 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001740 case OMPRTL__kmpc_reduce: {
1741 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1742 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1743 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1744 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1745 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1746 /*isVarArg=*/false);
1747 llvm::Type *TypeParams[] = {
1748 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1749 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1750 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1751 llvm::FunctionType *FnTy =
1752 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1753 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1754 break;
1755 }
1756 case OMPRTL__kmpc_reduce_nowait: {
1757 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1758 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1759 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1760 // *lck);
1761 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1762 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1763 /*isVarArg=*/false);
1764 llvm::Type *TypeParams[] = {
1765 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1766 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1767 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1768 llvm::FunctionType *FnTy =
1769 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1770 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1771 break;
1772 }
1773 case OMPRTL__kmpc_end_reduce: {
1774 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1775 // kmp_critical_name *lck);
1776 llvm::Type *TypeParams[] = {
1777 getIdentTyPointerTy(), CGM.Int32Ty,
1778 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1779 llvm::FunctionType *FnTy =
1780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1781 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1782 break;
1783 }
1784 case OMPRTL__kmpc_end_reduce_nowait: {
1785 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1786 // kmp_critical_name *lck);
1787 llvm::Type *TypeParams[] = {
1788 getIdentTyPointerTy(), CGM.Int32Ty,
1789 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1790 llvm::FunctionType *FnTy =
1791 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1792 RTLFn =
1793 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1794 break;
1795 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001796 case OMPRTL__kmpc_omp_task_begin_if0: {
1797 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1798 // *new_task);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1800 CGM.VoidPtrTy};
1801 llvm::FunctionType *FnTy =
1802 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1803 RTLFn =
1804 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1805 break;
1806 }
1807 case OMPRTL__kmpc_omp_task_complete_if0: {
1808 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1809 // *new_task);
1810 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1811 CGM.VoidPtrTy};
1812 llvm::FunctionType *FnTy =
1813 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1814 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1815 /*Name=*/"__kmpc_omp_task_complete_if0");
1816 break;
1817 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001818 case OMPRTL__kmpc_ordered: {
1819 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1820 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1821 llvm::FunctionType *FnTy =
1822 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1823 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1824 break;
1825 }
1826 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001827 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001828 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1829 llvm::FunctionType *FnTy =
1830 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1831 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1832 break;
1833 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001834 case OMPRTL__kmpc_omp_taskwait: {
1835 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1836 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1837 llvm::FunctionType *FnTy =
1838 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1839 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1840 break;
1841 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001842 case OMPRTL__kmpc_taskgroup: {
1843 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1845 llvm::FunctionType *FnTy =
1846 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1847 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1848 break;
1849 }
1850 case OMPRTL__kmpc_end_taskgroup: {
1851 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1852 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1853 llvm::FunctionType *FnTy =
1854 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1855 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1856 break;
1857 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001858 case OMPRTL__kmpc_push_proc_bind: {
1859 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1860 // int proc_bind)
1861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1862 llvm::FunctionType *FnTy =
1863 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1864 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1865 break;
1866 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001867 case OMPRTL__kmpc_omp_task_with_deps: {
1868 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1869 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1870 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1871 llvm::Type *TypeParams[] = {
1872 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1873 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1874 llvm::FunctionType *FnTy =
1875 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1876 RTLFn =
1877 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1878 break;
1879 }
1880 case OMPRTL__kmpc_omp_wait_deps: {
1881 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1882 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1883 // kmp_depend_info_t *noalias_dep_list);
1884 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1885 CGM.Int32Ty, CGM.VoidPtrTy,
1886 CGM.Int32Ty, CGM.VoidPtrTy};
1887 llvm::FunctionType *FnTy =
1888 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1889 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1890 break;
1891 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001892 case OMPRTL__kmpc_cancellationpoint: {
1893 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1894 // global_tid, kmp_int32 cncl_kind)
1895 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1896 llvm::FunctionType *FnTy =
1897 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1898 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1899 break;
1900 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001901 case OMPRTL__kmpc_cancel: {
1902 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1903 // kmp_int32 cncl_kind)
1904 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1905 llvm::FunctionType *FnTy =
1906 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1907 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1908 break;
1909 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001910 case OMPRTL__kmpc_push_num_teams: {
1911 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1912 // kmp_int32 num_teams, kmp_int32 num_threads)
1913 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1914 CGM.Int32Ty};
1915 llvm::FunctionType *FnTy =
1916 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1917 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1918 break;
1919 }
1920 case OMPRTL__kmpc_fork_teams: {
1921 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1922 // microtask, ...);
1923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1924 getKmpc_MicroPointerTy()};
1925 llvm::FunctionType *FnTy =
1926 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1927 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1928 break;
1929 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001930 case OMPRTL__kmpc_taskloop: {
1931 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1932 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1933 // sched, kmp_uint64 grainsize, void *task_dup);
1934 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1935 CGM.IntTy,
1936 CGM.VoidPtrTy,
1937 CGM.IntTy,
1938 CGM.Int64Ty->getPointerTo(),
1939 CGM.Int64Ty->getPointerTo(),
1940 CGM.Int64Ty,
1941 CGM.IntTy,
1942 CGM.IntTy,
1943 CGM.Int64Ty,
1944 CGM.VoidPtrTy};
1945 llvm::FunctionType *FnTy =
1946 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1947 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1948 break;
1949 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001950 case OMPRTL__kmpc_doacross_init: {
1951 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1952 // num_dims, struct kmp_dim *dims);
1953 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1954 CGM.Int32Ty,
1955 CGM.Int32Ty,
1956 CGM.VoidPtrTy};
1957 llvm::FunctionType *FnTy =
1958 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1959 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1960 break;
1961 }
1962 case OMPRTL__kmpc_doacross_fini: {
1963 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1964 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1965 llvm::FunctionType *FnTy =
1966 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1967 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1968 break;
1969 }
1970 case OMPRTL__kmpc_doacross_post: {
1971 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1972 // *vec);
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1974 CGM.Int64Ty->getPointerTo()};
1975 llvm::FunctionType *FnTy =
1976 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1977 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1978 break;
1979 }
1980 case OMPRTL__kmpc_doacross_wait: {
1981 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1982 // *vec);
1983 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1984 CGM.Int64Ty->getPointerTo()};
1985 llvm::FunctionType *FnTy =
1986 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1987 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1988 break;
1989 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001990 case OMPRTL__kmpc_task_reduction_init: {
1991 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1992 // *data);
1993 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1994 llvm::FunctionType *FnTy =
1995 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1996 RTLFn =
1997 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
1998 break;
1999 }
2000 case OMPRTL__kmpc_task_reduction_get_th_data: {
2001 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2002 // *d);
2003 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2004 llvm::FunctionType *FnTy =
2005 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2006 RTLFn = CGM.CreateRuntimeFunction(
2007 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2008 break;
2009 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002010 case OMPRTL__tgt_target: {
2011 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2012 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2013 // *arg_types);
2014 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2015 CGM.VoidPtrTy,
2016 CGM.Int32Ty,
2017 CGM.VoidPtrPtrTy,
2018 CGM.VoidPtrPtrTy,
2019 CGM.SizeTy->getPointerTo(),
2020 CGM.Int32Ty->getPointerTo()};
2021 llvm::FunctionType *FnTy =
2022 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2023 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2024 break;
2025 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002026 case OMPRTL__tgt_target_teams: {
2027 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2028 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2029 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2030 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2031 CGM.VoidPtrTy,
2032 CGM.Int32Ty,
2033 CGM.VoidPtrPtrTy,
2034 CGM.VoidPtrPtrTy,
2035 CGM.SizeTy->getPointerTo(),
2036 CGM.Int32Ty->getPointerTo(),
2037 CGM.Int32Ty,
2038 CGM.Int32Ty};
2039 llvm::FunctionType *FnTy =
2040 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2041 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2042 break;
2043 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002044 case OMPRTL__tgt_register_lib: {
2045 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2046 QualType ParamTy =
2047 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2048 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2049 llvm::FunctionType *FnTy =
2050 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2051 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2052 break;
2053 }
2054 case OMPRTL__tgt_unregister_lib: {
2055 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2056 QualType ParamTy =
2057 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2058 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2059 llvm::FunctionType *FnTy =
2060 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2061 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2062 break;
2063 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002064 case OMPRTL__tgt_target_data_begin: {
2065 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2066 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2067 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2068 CGM.Int32Ty,
2069 CGM.VoidPtrPtrTy,
2070 CGM.VoidPtrPtrTy,
2071 CGM.SizeTy->getPointerTo(),
2072 CGM.Int32Ty->getPointerTo()};
2073 llvm::FunctionType *FnTy =
2074 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2075 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2076 break;
2077 }
2078 case OMPRTL__tgt_target_data_end: {
2079 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2080 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2081 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2082 CGM.Int32Ty,
2083 CGM.VoidPtrPtrTy,
2084 CGM.VoidPtrPtrTy,
2085 CGM.SizeTy->getPointerTo(),
2086 CGM.Int32Ty->getPointerTo()};
2087 llvm::FunctionType *FnTy =
2088 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2089 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2090 break;
2091 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002092 case OMPRTL__tgt_target_data_update: {
2093 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2094 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2095 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2096 CGM.Int32Ty,
2097 CGM.VoidPtrPtrTy,
2098 CGM.VoidPtrPtrTy,
2099 CGM.SizeTy->getPointerTo(),
2100 CGM.Int32Ty->getPointerTo()};
2101 llvm::FunctionType *FnTy =
2102 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2103 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2104 break;
2105 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002106 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002107 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002108 return RTLFn;
2109}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002110
Alexander Musman21212e42015-03-13 10:38:23 +00002111llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2112 bool IVSigned) {
2113 assert((IVSize == 32 || IVSize == 64) &&
2114 "IV size is not compatible with the omp runtime");
2115 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2116 : "__kmpc_for_static_init_4u")
2117 : (IVSigned ? "__kmpc_for_static_init_8"
2118 : "__kmpc_for_static_init_8u");
2119 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2120 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2121 llvm::Type *TypeParams[] = {
2122 getIdentTyPointerTy(), // loc
2123 CGM.Int32Ty, // tid
2124 CGM.Int32Ty, // schedtype
2125 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2126 PtrTy, // p_lower
2127 PtrTy, // p_upper
2128 PtrTy, // p_stride
2129 ITy, // incr
2130 ITy // chunk
2131 };
2132 llvm::FunctionType *FnTy =
2133 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2134 return CGM.CreateRuntimeFunction(FnTy, Name);
2135}
2136
Alexander Musman92bdaab2015-03-12 13:37:50 +00002137llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2138 bool IVSigned) {
2139 assert((IVSize == 32 || IVSize == 64) &&
2140 "IV size is not compatible with the omp runtime");
2141 auto Name =
2142 IVSize == 32
2143 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2144 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2145 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2146 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2147 CGM.Int32Ty, // tid
2148 CGM.Int32Ty, // schedtype
2149 ITy, // lower
2150 ITy, // upper
2151 ITy, // stride
2152 ITy // chunk
2153 };
2154 llvm::FunctionType *FnTy =
2155 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2156 return CGM.CreateRuntimeFunction(FnTy, Name);
2157}
2158
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002159llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2160 bool IVSigned) {
2161 assert((IVSize == 32 || IVSize == 64) &&
2162 "IV size is not compatible with the omp runtime");
2163 auto Name =
2164 IVSize == 32
2165 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2166 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2167 llvm::Type *TypeParams[] = {
2168 getIdentTyPointerTy(), // loc
2169 CGM.Int32Ty, // tid
2170 };
2171 llvm::FunctionType *FnTy =
2172 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2173 return CGM.CreateRuntimeFunction(FnTy, Name);
2174}
2175
Alexander Musman92bdaab2015-03-12 13:37:50 +00002176llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2177 bool IVSigned) {
2178 assert((IVSize == 32 || IVSize == 64) &&
2179 "IV size is not compatible with the omp runtime");
2180 auto Name =
2181 IVSize == 32
2182 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2183 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2184 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2185 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2186 llvm::Type *TypeParams[] = {
2187 getIdentTyPointerTy(), // loc
2188 CGM.Int32Ty, // tid
2189 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2190 PtrTy, // p_lower
2191 PtrTy, // p_upper
2192 PtrTy // p_stride
2193 };
2194 llvm::FunctionType *FnTy =
2195 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2196 return CGM.CreateRuntimeFunction(FnTy, Name);
2197}
2198
Alexey Bataev97720002014-11-11 04:05:39 +00002199llvm::Constant *
2200CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002201 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2202 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002203 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002204 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002205 Twine(CGM.getMangledName(VD)) + ".cache.");
2206}
2207
John McCall7f416cc2015-09-08 08:05:57 +00002208Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2209 const VarDecl *VD,
2210 Address VDAddr,
2211 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002212 if (CGM.getLangOpts().OpenMPUseTLS &&
2213 CGM.getContext().getTargetInfo().isTLSSupported())
2214 return VDAddr;
2215
John McCall7f416cc2015-09-08 08:05:57 +00002216 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002217 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002218 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2219 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002220 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2221 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002222 return Address(CGF.EmitRuntimeCall(
2223 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2224 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002225}
2226
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002227void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002228 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002229 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2230 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2231 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002232 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2233 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002234 OMPLoc);
2235 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2236 // to register constructor/destructor for variable.
2237 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002238 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2239 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002240 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002241 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002242 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002243}
2244
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002245llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002246 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002247 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002248 if (CGM.getLangOpts().OpenMPUseTLS &&
2249 CGM.getContext().getTargetInfo().isTLSSupported())
2250 return nullptr;
2251
Alexey Bataev97720002014-11-11 04:05:39 +00002252 VD = VD->getDefinition(CGM.getContext());
2253 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2254 ThreadPrivateWithDefinition.insert(VD);
2255 QualType ASTTy = VD->getType();
2256
2257 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2258 auto Init = VD->getAnyInitializer();
2259 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2260 // Generate function that re-emits the declaration's initializer into the
2261 // threadprivate copy of the variable VD
2262 CodeGenFunction CtorCGF(CGM);
2263 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002264 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2265 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002266 Args.push_back(&Dst);
2267
John McCallc56a8b32016-03-11 04:30:31 +00002268 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2269 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002270 auto FTy = CGM.getTypes().GetFunctionType(FI);
2271 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002272 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002273 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2274 Args, SourceLocation());
2275 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002276 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002277 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002278 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2279 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2280 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002281 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2282 /*IsInitializer=*/true);
2283 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002284 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002285 CGM.getContext().VoidPtrTy, Dst.getLocation());
2286 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2287 CtorCGF.FinishFunction();
2288 Ctor = Fn;
2289 }
2290 if (VD->getType().isDestructedType() != QualType::DK_none) {
2291 // Generate function that emits destructor call for the threadprivate copy
2292 // of the variable VD
2293 CodeGenFunction DtorCGF(CGM);
2294 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002295 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2296 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002297 Args.push_back(&Dst);
2298
John McCallc56a8b32016-03-11 04:30:31 +00002299 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2300 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002301 auto FTy = CGM.getTypes().GetFunctionType(FI);
2302 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002303 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002304 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002305 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2306 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002307 // Create a scope with an artificial location for the body of this function.
2308 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002309 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2310 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002311 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2312 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002313 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2314 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2315 DtorCGF.FinishFunction();
2316 Dtor = Fn;
2317 }
2318 // Do not emit init function if it is not required.
2319 if (!Ctor && !Dtor)
2320 return nullptr;
2321
2322 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2323 auto CopyCtorTy =
2324 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2325 /*isVarArg=*/false)->getPointerTo();
2326 // Copying constructor for the threadprivate variable.
2327 // Must be NULL - reserved by runtime, but currently it requires that this
2328 // parameter is always NULL. Otherwise it fires assertion.
2329 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2330 if (Ctor == nullptr) {
2331 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2332 /*isVarArg=*/false)->getPointerTo();
2333 Ctor = llvm::Constant::getNullValue(CtorTy);
2334 }
2335 if (Dtor == nullptr) {
2336 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2337 /*isVarArg=*/false)->getPointerTo();
2338 Dtor = llvm::Constant::getNullValue(DtorTy);
2339 }
2340 if (!CGF) {
2341 auto InitFunctionTy =
2342 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2343 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002344 InitFunctionTy, ".__omp_threadprivate_init_.",
2345 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002346 CodeGenFunction InitCGF(CGM);
2347 FunctionArgList ArgList;
2348 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2349 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2350 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002351 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002352 InitCGF.FinishFunction();
2353 return InitFunction;
2354 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002355 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002356 }
2357 return nullptr;
2358}
2359
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002360Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2361 QualType VarType,
2362 StringRef Name) {
2363 llvm::Twine VarName(Name, ".artificial.");
2364 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2365 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2366 llvm::Value *Args[] = {
2367 emitUpdateLocation(CGF, SourceLocation()),
2368 getThreadID(CGF, SourceLocation()),
2369 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2370 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2371 /*IsSigned=*/false),
2372 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2373 return Address(
2374 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2375 CGF.EmitRuntimeCall(
2376 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2377 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2378 CGM.getPointerAlign());
2379}
2380
Alexey Bataev1d677132015-04-22 13:57:31 +00002381/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2382/// function. Here is the logic:
2383/// if (Cond) {
2384/// ThenGen();
2385/// } else {
2386/// ElseGen();
2387/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002388void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2389 const RegionCodeGenTy &ThenGen,
2390 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002391 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2392
2393 // If the condition constant folds and can be elided, try to avoid emitting
2394 // the condition and the dead arm of the if/else.
2395 bool CondConstant;
2396 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002397 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002398 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002399 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002400 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002401 return;
2402 }
2403
2404 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2405 // emit the conditional branch.
2406 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2407 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2408 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2409 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2410
2411 // Emit the 'then' code.
2412 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002413 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002414 CGF.EmitBranch(ContBlock);
2415 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002416 // There is no need to emit line number for unconditional branch.
2417 (void)ApplyDebugLocation::CreateEmpty(CGF);
2418 CGF.EmitBlock(ElseBlock);
2419 ElseGen(CGF);
2420 // There is no need to emit line number for unconditional branch.
2421 (void)ApplyDebugLocation::CreateEmpty(CGF);
2422 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002423 // Emit the continuation block for code after the if.
2424 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002425}
2426
Alexey Bataev1d677132015-04-22 13:57:31 +00002427void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2428 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002429 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002430 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002431 if (!CGF.HaveInsertPoint())
2432 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002433 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002434 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2435 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002436 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002437 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002438 llvm::Value *Args[] = {
2439 RTLoc,
2440 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002441 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002442 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2443 RealArgs.append(std::begin(Args), std::end(Args));
2444 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2445
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002446 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002447 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2448 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002449 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2450 PrePostActionTy &) {
2451 auto &RT = CGF.CGM.getOpenMPRuntime();
2452 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002453 // Build calls:
2454 // __kmpc_serialized_parallel(&Loc, GTid);
2455 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002456 CGF.EmitRuntimeCall(
2457 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002458
Alexey Bataev1d677132015-04-22 13:57:31 +00002459 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002460 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002461 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002462 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2463 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002464 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002465 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2466 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2467 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2468 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002469 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002470
Alexey Bataev1d677132015-04-22 13:57:31 +00002471 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002472 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002473 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002474 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2475 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002476 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002477 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002478 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002479 else {
2480 RegionCodeGenTy ThenRCG(ThenGen);
2481 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002482 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002483}
2484
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002485// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002486// thread-ID variable (it is passed in a first argument of the outlined function
2487// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2488// regular serial code region, get thread ID by calling kmp_int32
2489// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2490// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002491Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2492 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002493 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002494 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002495 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002496 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002497
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002498 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002499 auto Int32Ty =
2500 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2501 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2502 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002503 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002504
2505 return ThreadIDTemp;
2506}
2507
Alexey Bataev97720002014-11-11 04:05:39 +00002508llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002509CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002510 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002511 SmallString<256> Buffer;
2512 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002513 Out << Name;
2514 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002515 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2516 if (Elem.second) {
2517 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002518 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002519 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002520 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002521
David Blaikie13156b62014-11-19 03:06:06 +00002522 return Elem.second = new llvm::GlobalVariable(
2523 CGM.getModule(), Ty, /*IsConstant*/ false,
2524 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2525 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002526}
2527
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002528llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002529 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002530 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002531}
2532
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002533namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002534/// Common pre(post)-action for different OpenMP constructs.
2535class CommonActionTy final : public PrePostActionTy {
2536 llvm::Value *EnterCallee;
2537 ArrayRef<llvm::Value *> EnterArgs;
2538 llvm::Value *ExitCallee;
2539 ArrayRef<llvm::Value *> ExitArgs;
2540 bool Conditional;
2541 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002542
2543public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002544 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2545 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2546 bool Conditional = false)
2547 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2548 ExitArgs(ExitArgs), Conditional(Conditional) {}
2549 void Enter(CodeGenFunction &CGF) override {
2550 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2551 if (Conditional) {
2552 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2553 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2554 ContBlock = CGF.createBasicBlock("omp_if.end");
2555 // Generate the branch (If-stmt)
2556 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2557 CGF.EmitBlock(ThenBlock);
2558 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002559 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002560 void Done(CodeGenFunction &CGF) {
2561 // Emit the rest of blocks/branches
2562 CGF.EmitBranch(ContBlock);
2563 CGF.EmitBlock(ContBlock, true);
2564 }
2565 void Exit(CodeGenFunction &CGF) override {
2566 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002567 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002568};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002569} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002570
2571void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2572 StringRef CriticalName,
2573 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002574 SourceLocation Loc, const Expr *Hint) {
2575 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002576 // CriticalOpGen();
2577 // __kmpc_end_critical(ident_t *, gtid, Lock);
2578 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002579 if (!CGF.HaveInsertPoint())
2580 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002581 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2582 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002583 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2584 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002585 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002586 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2587 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2588 }
2589 CommonActionTy Action(
2590 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2591 : OMPRTL__kmpc_critical),
2592 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2593 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002594 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002595}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002596
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002597void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002598 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002599 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002600 if (!CGF.HaveInsertPoint())
2601 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002602 // if(__kmpc_master(ident_t *, gtid)) {
2603 // MasterOpGen();
2604 // __kmpc_end_master(ident_t *, gtid);
2605 // }
2606 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002607 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002608 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2609 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2610 /*Conditional=*/true);
2611 MasterOpGen.setAction(Action);
2612 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2613 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002614}
2615
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002616void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2617 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002618 if (!CGF.HaveInsertPoint())
2619 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002620 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2621 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002622 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002623 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002624 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002625 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2626 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002627}
2628
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002629void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2630 const RegionCodeGenTy &TaskgroupOpGen,
2631 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002632 if (!CGF.HaveInsertPoint())
2633 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002634 // __kmpc_taskgroup(ident_t *, gtid);
2635 // TaskgroupOpGen();
2636 // __kmpc_end_taskgroup(ident_t *, gtid);
2637 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002638 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2639 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2640 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2641 Args);
2642 TaskgroupOpGen.setAction(Action);
2643 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002644}
2645
John McCall7f416cc2015-09-08 08:05:57 +00002646/// Given an array of pointers to variables, project the address of a
2647/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002648static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2649 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002650 // Pull out the pointer to the variable.
2651 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002652 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002653 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2654
2655 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002656 Addr = CGF.Builder.CreateElementBitCast(
2657 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002658 return Addr;
2659}
2660
Alexey Bataeva63048e2015-03-23 06:18:07 +00002661static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002662 CodeGenModule &CGM, llvm::Type *ArgsType,
2663 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2664 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002665 auto &C = CGM.getContext();
2666 // void copy_func(void *LHSArg, void *RHSArg);
2667 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002668 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2669 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002670 Args.push_back(&LHSArg);
2671 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002672 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002673 auto *Fn = llvm::Function::Create(
2674 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2675 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002676 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002677 CodeGenFunction CGF(CGM);
2678 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002679 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002680 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002681 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2682 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2683 ArgsType), CGF.getPointerAlign());
2684 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2685 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2686 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002687 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2688 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2689 // ...
2690 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002691 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002692 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2693 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2694
2695 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2696 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2697
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002698 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2699 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002700 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002701 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002702 CGF.FinishFunction();
2703 return Fn;
2704}
2705
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002706void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002707 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002708 SourceLocation Loc,
2709 ArrayRef<const Expr *> CopyprivateVars,
2710 ArrayRef<const Expr *> SrcExprs,
2711 ArrayRef<const Expr *> DstExprs,
2712 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002713 if (!CGF.HaveInsertPoint())
2714 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002715 assert(CopyprivateVars.size() == SrcExprs.size() &&
2716 CopyprivateVars.size() == DstExprs.size() &&
2717 CopyprivateVars.size() == AssignmentOps.size());
2718 auto &C = CGM.getContext();
2719 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002720 // if(__kmpc_single(ident_t *, gtid)) {
2721 // SingleOpGen();
2722 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002723 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002724 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002725 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2726 // <copy_func>, did_it);
2727
John McCall7f416cc2015-09-08 08:05:57 +00002728 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002729 if (!CopyprivateVars.empty()) {
2730 // int32 did_it = 0;
2731 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2732 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002733 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002734 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002735 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002736 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002737 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2738 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2739 /*Conditional=*/true);
2740 SingleOpGen.setAction(Action);
2741 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2742 if (DidIt.isValid()) {
2743 // did_it = 1;
2744 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2745 }
2746 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002747 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2748 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002749 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002750 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2751 auto CopyprivateArrayTy =
2752 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2753 /*IndexTypeQuals=*/0);
2754 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002755 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002756 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2757 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002758 Address Elem = CGF.Builder.CreateConstArrayGEP(
2759 CopyprivateList, I, CGF.getPointerSize());
2760 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002761 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002762 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2763 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002764 }
2765 // Build function that copies private values from single region to all other
2766 // threads in the corresponding parallel region.
2767 auto *CpyFn = emitCopyprivateCopyFunction(
2768 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002769 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002770 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002771 Address CL =
2772 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2773 CGF.VoidPtrTy);
2774 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002775 llvm::Value *Args[] = {
2776 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2777 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002778 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002779 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002780 CpyFn, // void (*) (void *, void *) <copy_func>
2781 DidItVal // i32 did_it
2782 };
2783 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2784 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002785}
2786
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002787void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2788 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002789 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002790 if (!CGF.HaveInsertPoint())
2791 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002792 // __kmpc_ordered(ident_t *, gtid);
2793 // OrderedOpGen();
2794 // __kmpc_end_ordered(ident_t *, gtid);
2795 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002796 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002797 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002798 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2799 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2800 Args);
2801 OrderedOpGen.setAction(Action);
2802 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2803 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002804 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002805 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002806}
2807
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002808void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002809 OpenMPDirectiveKind Kind, bool EmitChecks,
2810 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002811 if (!CGF.HaveInsertPoint())
2812 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002813 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002814 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002815 unsigned Flags;
2816 if (Kind == OMPD_for)
2817 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2818 else if (Kind == OMPD_sections)
2819 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2820 else if (Kind == OMPD_single)
2821 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2822 else if (Kind == OMPD_barrier)
2823 Flags = OMP_IDENT_BARRIER_EXPL;
2824 else
2825 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002826 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2827 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002828 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2829 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002830 if (auto *OMPRegionInfo =
2831 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002832 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002833 auto *Result = CGF.EmitRuntimeCall(
2834 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002835 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002836 // if (__kmpc_cancel_barrier()) {
2837 // exit from construct;
2838 // }
2839 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2840 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2841 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2842 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2843 CGF.EmitBlock(ExitBB);
2844 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002845 auto CancelDestination =
2846 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002847 CGF.EmitBranchThroughCleanup(CancelDestination);
2848 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2849 }
2850 return;
2851 }
2852 }
2853 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002854}
2855
Alexander Musmanc6388682014-12-15 07:07:06 +00002856/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2857static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002858 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002859 switch (ScheduleKind) {
2860 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002861 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2862 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002863 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002864 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002865 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002866 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002867 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002868 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2869 case OMPC_SCHEDULE_auto:
2870 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002871 case OMPC_SCHEDULE_unknown:
2872 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002873 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002874 }
2875 llvm_unreachable("Unexpected runtime schedule");
2876}
2877
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002878/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2879static OpenMPSchedType
2880getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2881 // only static is allowed for dist_schedule
2882 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2883}
2884
Alexander Musmanc6388682014-12-15 07:07:06 +00002885bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2886 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002887 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002888 return Schedule == OMP_sch_static;
2889}
2890
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002891bool CGOpenMPRuntime::isStaticNonchunked(
2892 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2893 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2894 return Schedule == OMP_dist_sch_static;
2895}
2896
2897
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002898bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002899 auto Schedule =
2900 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002901 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2902 return Schedule != OMP_sch_static;
2903}
2904
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002905static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2906 OpenMPScheduleClauseModifier M1,
2907 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002908 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002909 switch (M1) {
2910 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002911 Modifier = OMP_sch_modifier_monotonic;
2912 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002913 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002914 Modifier = OMP_sch_modifier_nonmonotonic;
2915 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002916 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002917 if (Schedule == OMP_sch_static_chunked)
2918 Schedule = OMP_sch_static_balanced_chunked;
2919 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002920 case OMPC_SCHEDULE_MODIFIER_last:
2921 case OMPC_SCHEDULE_MODIFIER_unknown:
2922 break;
2923 }
2924 switch (M2) {
2925 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002926 Modifier = OMP_sch_modifier_monotonic;
2927 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002928 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002929 Modifier = OMP_sch_modifier_nonmonotonic;
2930 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002931 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002932 if (Schedule == OMP_sch_static_chunked)
2933 Schedule = OMP_sch_static_balanced_chunked;
2934 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002935 case OMPC_SCHEDULE_MODIFIER_last:
2936 case OMPC_SCHEDULE_MODIFIER_unknown:
2937 break;
2938 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002939 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002940}
2941
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002942void CGOpenMPRuntime::emitForDispatchInit(
2943 CodeGenFunction &CGF, SourceLocation Loc,
2944 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2945 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002946 if (!CGF.HaveInsertPoint())
2947 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002948 OpenMPSchedType Schedule = getRuntimeSchedule(
2949 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002950 assert(Ordered ||
2951 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002952 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2953 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002954 // Call __kmpc_dispatch_init(
2955 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2956 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2957 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002958
John McCall7f416cc2015-09-08 08:05:57 +00002959 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002960 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2961 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002962 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002963 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2964 CGF.Builder.getInt32(addMonoNonMonoModifier(
2965 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002966 DispatchValues.LB, // Lower
2967 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002968 CGF.Builder.getIntN(IVSize, 1), // Stride
2969 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002970 };
2971 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2972}
2973
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002974static void emitForStaticInitCall(
2975 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2976 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2977 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002978 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002979 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002980 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002981
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002982 assert(!Values.Ordered);
2983 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2984 Schedule == OMP_sch_static_balanced_chunked ||
2985 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2986 Schedule == OMP_dist_sch_static ||
2987 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002988
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002989 // Call __kmpc_for_static_init(
2990 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2991 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2992 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2993 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2994 llvm::Value *Chunk = Values.Chunk;
2995 if (Chunk == nullptr) {
2996 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2997 Schedule == OMP_dist_sch_static) &&
2998 "expected static non-chunked schedule");
2999 // If the Chunk was not specified in the clause - use default value 1.
3000 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3001 } else {
3002 assert((Schedule == OMP_sch_static_chunked ||
3003 Schedule == OMP_sch_static_balanced_chunked ||
3004 Schedule == OMP_ord_static_chunked ||
3005 Schedule == OMP_dist_sch_static_chunked) &&
3006 "expected static chunked schedule");
3007 }
3008 llvm::Value *Args[] = {
3009 UpdateLocation,
3010 ThreadId,
3011 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3012 M2)), // Schedule type
3013 Values.IL.getPointer(), // &isLastIter
3014 Values.LB.getPointer(), // &LB
3015 Values.UB.getPointer(), // &UB
3016 Values.ST.getPointer(), // &Stride
3017 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3018 Chunk // Chunk
3019 };
3020 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003021}
3022
John McCall7f416cc2015-09-08 08:05:57 +00003023void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3024 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003025 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003026 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003027 const StaticRTInput &Values) {
3028 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3029 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3030 assert(isOpenMPWorksharingDirective(DKind) &&
3031 "Expected loop-based or sections-based directive.");
3032 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3033 isOpenMPLoopDirective(DKind)
3034 ? OMP_IDENT_WORK_LOOP
3035 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003036 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003037 auto *StaticInitFunction =
3038 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003039 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003040 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003041}
John McCall7f416cc2015-09-08 08:05:57 +00003042
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003043void CGOpenMPRuntime::emitDistributeStaticInit(
3044 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003045 OpenMPDistScheduleClauseKind SchedKind,
3046 const CGOpenMPRuntime::StaticRTInput &Values) {
3047 OpenMPSchedType ScheduleNum =
3048 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3049 auto *UpdatedLocation =
3050 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003051 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003052 auto *StaticInitFunction =
3053 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003054 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3055 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003056 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003057}
3058
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003059void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003060 SourceLocation Loc,
3061 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003062 if (!CGF.HaveInsertPoint())
3063 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003064 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003065 llvm::Value *Args[] = {
3066 emitUpdateLocation(CGF, Loc,
3067 isOpenMPDistributeDirective(DKind)
3068 ? OMP_IDENT_WORK_DISTRIBUTE
3069 : isOpenMPLoopDirective(DKind)
3070 ? OMP_IDENT_WORK_LOOP
3071 : OMP_IDENT_WORK_SECTIONS),
3072 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003073 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3074 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003075}
3076
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003077void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3078 SourceLocation Loc,
3079 unsigned IVSize,
3080 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003081 if (!CGF.HaveInsertPoint())
3082 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003083 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003084 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003085 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3086}
3087
Alexander Musman92bdaab2015-03-12 13:37:50 +00003088llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3089 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003090 bool IVSigned, Address IL,
3091 Address LB, Address UB,
3092 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003093 // Call __kmpc_dispatch_next(
3094 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3095 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3096 // kmp_int[32|64] *p_stride);
3097 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003098 emitUpdateLocation(CGF, Loc),
3099 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003100 IL.getPointer(), // &isLastIter
3101 LB.getPointer(), // &Lower
3102 UB.getPointer(), // &Upper
3103 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003104 };
3105 llvm::Value *Call =
3106 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3107 return CGF.EmitScalarConversion(
3108 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003109 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003110}
3111
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003112void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3113 llvm::Value *NumThreads,
3114 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003115 if (!CGF.HaveInsertPoint())
3116 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003117 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3118 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003119 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003120 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003121 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3122 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003123}
3124
Alexey Bataev7f210c62015-06-18 13:40:03 +00003125void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3126 OpenMPProcBindClauseKind ProcBind,
3127 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003128 if (!CGF.HaveInsertPoint())
3129 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003130 // Constants for proc bind value accepted by the runtime.
3131 enum ProcBindTy {
3132 ProcBindFalse = 0,
3133 ProcBindTrue,
3134 ProcBindMaster,
3135 ProcBindClose,
3136 ProcBindSpread,
3137 ProcBindIntel,
3138 ProcBindDefault
3139 } RuntimeProcBind;
3140 switch (ProcBind) {
3141 case OMPC_PROC_BIND_master:
3142 RuntimeProcBind = ProcBindMaster;
3143 break;
3144 case OMPC_PROC_BIND_close:
3145 RuntimeProcBind = ProcBindClose;
3146 break;
3147 case OMPC_PROC_BIND_spread:
3148 RuntimeProcBind = ProcBindSpread;
3149 break;
3150 case OMPC_PROC_BIND_unknown:
3151 llvm_unreachable("Unsupported proc_bind value.");
3152 }
3153 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3154 llvm::Value *Args[] = {
3155 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3156 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3157 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3158}
3159
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003160void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3161 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003162 if (!CGF.HaveInsertPoint())
3163 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003164 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003165 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3166 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003167}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003168
Alexey Bataev62b63b12015-03-10 07:28:44 +00003169namespace {
3170/// \brief Indexes of fields for type kmp_task_t.
3171enum KmpTaskTFields {
3172 /// \brief List of shared variables.
3173 KmpTaskTShareds,
3174 /// \brief Task routine.
3175 KmpTaskTRoutine,
3176 /// \brief Partition id for the untied tasks.
3177 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003178 /// Function with call of destructors for private variables.
3179 Data1,
3180 /// Task priority.
3181 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003182 /// (Taskloops only) Lower bound.
3183 KmpTaskTLowerBound,
3184 /// (Taskloops only) Upper bound.
3185 KmpTaskTUpperBound,
3186 /// (Taskloops only) Stride.
3187 KmpTaskTStride,
3188 /// (Taskloops only) Is last iteration flag.
3189 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003190 /// (Taskloops only) Reduction data.
3191 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003192};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003193} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003194
Samuel Antaoee8fb302016-01-06 13:42:12 +00003195bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3196 // FIXME: Add other entries type when they become supported.
3197 return OffloadEntriesTargetRegion.empty();
3198}
3199
3200/// \brief Initialize target region entry.
3201void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3202 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3203 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003204 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003205 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3206 "only required for the device "
3207 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003208 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003209 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3210 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003211 ++OffloadingEntriesNum;
3212}
3213
3214void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3215 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3216 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003217 llvm::Constant *Addr, llvm::Constant *ID,
3218 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003219 // If we are emitting code for a target, the entry is already initialized,
3220 // only has to be registered.
3221 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003222 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003223 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003224 auto &Entry =
3225 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003226 assert(Entry.isValid() && "Entry not initialized!");
3227 Entry.setAddress(Addr);
3228 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003229 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003230 return;
3231 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003232 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003233 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003234 }
3235}
3236
3237bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003238 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3239 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003240 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3241 if (PerDevice == OffloadEntriesTargetRegion.end())
3242 return false;
3243 auto PerFile = PerDevice->second.find(FileID);
3244 if (PerFile == PerDevice->second.end())
3245 return false;
3246 auto PerParentName = PerFile->second.find(ParentName);
3247 if (PerParentName == PerFile->second.end())
3248 return false;
3249 auto PerLine = PerParentName->second.find(LineNum);
3250 if (PerLine == PerParentName->second.end())
3251 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003252 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003253 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003254 return false;
3255 return true;
3256}
3257
3258void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3259 const OffloadTargetRegionEntryInfoActTy &Action) {
3260 // Scan all target region entries and perform the provided action.
3261 for (auto &D : OffloadEntriesTargetRegion)
3262 for (auto &F : D.second)
3263 for (auto &P : F.second)
3264 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003265 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003266}
3267
3268/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3269/// \a Codegen. This is used to emit the two functions that register and
3270/// unregister the descriptor of the current compilation unit.
3271static llvm::Function *
3272createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3273 const RegionCodeGenTy &Codegen) {
3274 auto &C = CGM.getContext();
3275 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003276 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003277 Args.push_back(&DummyPtr);
3278
3279 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003280 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003281 auto FTy = CGM.getTypes().GetFunctionType(FI);
3282 auto *Fn =
3283 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3284 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3285 Codegen(CGF);
3286 CGF.FinishFunction();
3287 return Fn;
3288}
3289
3290llvm::Function *
3291CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3292
3293 // If we don't have entries or if we are emitting code for the device, we
3294 // don't need to do anything.
3295 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3296 return nullptr;
3297
3298 auto &M = CGM.getModule();
3299 auto &C = CGM.getContext();
3300
3301 // Get list of devices we care about
3302 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3303
3304 // We should be creating an offloading descriptor only if there are devices
3305 // specified.
3306 assert(!Devices.empty() && "No OpenMP offloading devices??");
3307
3308 // Create the external variables that will point to the begin and end of the
3309 // host entries section. These will be defined by the linker.
3310 auto *OffloadEntryTy =
3311 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3312 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3313 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003314 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003315 ".omp_offloading.entries_begin");
3316 llvm::GlobalVariable *HostEntriesEnd = 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_end");
3320
3321 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003322 auto *DeviceImageTy = cast<llvm::StructType>(
3323 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003324 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003325 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003326
3327 for (unsigned i = 0; i < Devices.size(); ++i) {
3328 StringRef T = Devices[i].getTriple();
3329 auto *ImgBegin = new llvm::GlobalVariable(
3330 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003331 /*Initializer=*/nullptr,
3332 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003333 auto *ImgEnd = new llvm::GlobalVariable(
3334 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003335 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003336
John McCall6c9f1fdb2016-11-19 08:17:24 +00003337 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3338 Dev.add(ImgBegin);
3339 Dev.add(ImgEnd);
3340 Dev.add(HostEntriesBegin);
3341 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003342 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003343 }
3344
3345 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003346 llvm::GlobalVariable *DeviceImages =
3347 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3348 CGM.getPointerAlign(),
3349 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003350 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003351
3352 // This is a Zero array to be used in the creation of the constant expressions
3353 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3354 llvm::Constant::getNullValue(CGM.Int32Ty)};
3355
3356 // Create the target region descriptor.
3357 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3358 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003359 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003360 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3361 DescInit.addInt(CGM.Int32Ty, Devices.size());
3362 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3363 DeviceImages,
3364 Index));
3365 DescInit.add(HostEntriesBegin);
3366 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003367
John McCall6c9f1fdb2016-11-19 08:17:24 +00003368 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3369 CGM.getPointerAlign(),
3370 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003371
3372 // Emit code to register or unregister the descriptor at execution
3373 // startup or closing, respectively.
3374
3375 // Create a variable to drive the registration and unregistration of the
3376 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3377 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3378 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003379 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003380
3381 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003382 CGM, ".omp_offloading.descriptor_unreg",
3383 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003384 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3385 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003386 });
3387 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003388 CGM, ".omp_offloading.descriptor_reg",
3389 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003390 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3391 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003392 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3393 });
George Rokos29d0f002017-05-27 03:03:13 +00003394 if (CGM.supportsCOMDAT()) {
3395 // It is sufficient to call registration function only once, so create a
3396 // COMDAT group for registration/unregistration functions and associated
3397 // data. That would reduce startup time and code size. Registration
3398 // function serves as a COMDAT group key.
3399 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3400 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3401 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3402 RegFn->setComdat(ComdatKey);
3403 UnRegFn->setComdat(ComdatKey);
3404 DeviceImages->setComdat(ComdatKey);
3405 Desc->setComdat(ComdatKey);
3406 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003407 return RegFn;
3408}
3409
Samuel Antao2de62b02016-02-13 23:35:10 +00003410void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003411 llvm::Constant *Addr, uint64_t Size,
3412 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003413 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003414 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3415 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3416 llvm::LLVMContext &C = CGM.getModule().getContext();
3417 llvm::Module &M = CGM.getModule();
3418
3419 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003420 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003421
3422 // Create constant string with the name.
3423 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3424
3425 llvm::GlobalVariable *Str =
3426 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3427 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3428 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003429 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003430 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3431
John McCall6c9f1fdb2016-11-19 08:17:24 +00003432 // We can't have any padding between symbols, so we need to have 1-byte
3433 // alignment.
3434 auto Align = CharUnits::fromQuantity(1);
3435
Samuel Antaoee8fb302016-01-06 13:42:12 +00003436 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003437 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003438 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3439 EntryInit.add(AddrPtr);
3440 EntryInit.add(StrPtr);
3441 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003442 EntryInit.addInt(CGM.Int32Ty, Flags);
3443 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003444 llvm::GlobalVariable *Entry =
3445 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3446 Align,
3447 /*constant*/ true,
3448 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003449
3450 // The entry has to be created in the section the linker expects it to be.
3451 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003452}
3453
3454void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3455 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003456 // can easily figure out what to emit. The produced metadata looks like
3457 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003458 //
3459 // !omp_offload.info = !{!1, ...}
3460 //
3461 // Right now we only generate metadata for function that contain target
3462 // regions.
3463
3464 // If we do not have entries, we dont need to do anything.
3465 if (OffloadEntriesInfoManager.empty())
3466 return;
3467
3468 llvm::Module &M = CGM.getModule();
3469 llvm::LLVMContext &C = M.getContext();
3470 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3471 OrderedEntries(OffloadEntriesInfoManager.size());
3472
3473 // Create the offloading info metadata node.
3474 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3475
Simon Pilgrim2c518802017-03-30 14:13:19 +00003476 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003477 auto getMDInt = [&](unsigned v) {
3478 return llvm::ConstantAsMetadata::get(
3479 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3480 };
3481
3482 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3483
3484 // Create function that emits metadata for each target region entry;
3485 auto &&TargetRegionMetadataEmitter = [&](
3486 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003487 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3488 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3489 // Generate metadata for target regions. Each entry of this metadata
3490 // contains:
3491 // - Entry 0 -> Kind of this type of metadata (0).
3492 // - Entry 1 -> Device ID of the file where the entry was identified.
3493 // - Entry 2 -> File ID of the file where the entry was identified.
3494 // - Entry 3 -> Mangled name of the function where the entry was identified.
3495 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003496 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003497 // The first element of the metadata node is the kind.
3498 Ops.push_back(getMDInt(E.getKind()));
3499 Ops.push_back(getMDInt(DeviceID));
3500 Ops.push_back(getMDInt(FileID));
3501 Ops.push_back(getMDString(ParentName));
3502 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003503 Ops.push_back(getMDInt(E.getOrder()));
3504
3505 // Save this entry in the right position of the ordered entries array.
3506 OrderedEntries[E.getOrder()] = &E;
3507
3508 // Add metadata to the named metadata node.
3509 MD->addOperand(llvm::MDNode::get(C, Ops));
3510 };
3511
3512 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3513 TargetRegionMetadataEmitter);
3514
3515 for (auto *E : OrderedEntries) {
3516 assert(E && "All ordered entries must exist!");
3517 if (auto *CE =
3518 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3519 E)) {
3520 assert(CE->getID() && CE->getAddress() &&
3521 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003522 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003523 } else
3524 llvm_unreachable("Unsupported entry kind.");
3525 }
3526}
3527
3528/// \brief Loads all the offload entries information from the host IR
3529/// metadata.
3530void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3531 // If we are in target mode, load the metadata from the host IR. This code has
3532 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3533
3534 if (!CGM.getLangOpts().OpenMPIsDevice)
3535 return;
3536
3537 if (CGM.getLangOpts().OMPHostIRFile.empty())
3538 return;
3539
3540 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3541 if (Buf.getError())
3542 return;
3543
3544 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003545 auto ME = expectedToErrorOrAndEmitErrors(
3546 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003547
3548 if (ME.getError())
3549 return;
3550
3551 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3552 if (!MD)
3553 return;
3554
3555 for (auto I : MD->operands()) {
3556 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3557
3558 auto getMDInt = [&](unsigned Idx) {
3559 llvm::ConstantAsMetadata *V =
3560 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3561 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3562 };
3563
3564 auto getMDString = [&](unsigned Idx) {
3565 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3566 return V->getString();
3567 };
3568
3569 switch (getMDInt(0)) {
3570 default:
3571 llvm_unreachable("Unexpected metadata!");
3572 break;
3573 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3574 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3575 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3576 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3577 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003578 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003579 break;
3580 }
3581 }
3582}
3583
Alexey Bataev62b63b12015-03-10 07:28:44 +00003584void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3585 if (!KmpRoutineEntryPtrTy) {
3586 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3587 auto &C = CGM.getContext();
3588 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3589 FunctionProtoType::ExtProtoInfo EPI;
3590 KmpRoutineEntryPtrQTy = C.getPointerType(
3591 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3592 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3593 }
3594}
3595
Alexey Bataevc71a4092015-09-11 10:29:41 +00003596static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3597 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003598 auto *Field = FieldDecl::Create(
3599 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3600 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3601 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3602 Field->setAccess(AS_public);
3603 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003604 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003605}
3606
Samuel Antaoee8fb302016-01-06 13:42:12 +00003607QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3608
3609 // Make sure the type of the entry is already created. This is the type we
3610 // have to create:
3611 // struct __tgt_offload_entry{
3612 // void *addr; // Pointer to the offload entry info.
3613 // // (function or global)
3614 // char *name; // Name of the function or global.
3615 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003616 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3617 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003618 // };
3619 if (TgtOffloadEntryQTy.isNull()) {
3620 ASTContext &C = CGM.getContext();
3621 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3622 RD->startDefinition();
3623 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3624 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3625 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003626 addFieldToRecordDecl(
3627 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3628 addFieldToRecordDecl(
3629 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003630 RD->completeDefinition();
3631 TgtOffloadEntryQTy = C.getRecordType(RD);
3632 }
3633 return TgtOffloadEntryQTy;
3634}
3635
3636QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3637 // These are the types we need to build:
3638 // struct __tgt_device_image{
3639 // void *ImageStart; // Pointer to the target code start.
3640 // void *ImageEnd; // Pointer to the target code end.
3641 // // We also add the host entries to the device image, as it may be useful
3642 // // for the target runtime to have access to that information.
3643 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3644 // // the entries.
3645 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3646 // // entries (non inclusive).
3647 // };
3648 if (TgtDeviceImageQTy.isNull()) {
3649 ASTContext &C = CGM.getContext();
3650 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3651 RD->startDefinition();
3652 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3653 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3654 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3655 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3656 RD->completeDefinition();
3657 TgtDeviceImageQTy = C.getRecordType(RD);
3658 }
3659 return TgtDeviceImageQTy;
3660}
3661
3662QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3663 // struct __tgt_bin_desc{
3664 // int32_t NumDevices; // Number of devices supported.
3665 // __tgt_device_image *DeviceImages; // Arrays of device images
3666 // // (one per device).
3667 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3668 // // entries.
3669 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3670 // // entries (non inclusive).
3671 // };
3672 if (TgtBinaryDescriptorQTy.isNull()) {
3673 ASTContext &C = CGM.getContext();
3674 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3675 RD->startDefinition();
3676 addFieldToRecordDecl(
3677 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3678 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3679 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3680 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3681 RD->completeDefinition();
3682 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3683 }
3684 return TgtBinaryDescriptorQTy;
3685}
3686
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003687namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003688struct PrivateHelpersTy {
3689 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3690 const VarDecl *PrivateElemInit)
3691 : Original(Original), PrivateCopy(PrivateCopy),
3692 PrivateElemInit(PrivateElemInit) {}
3693 const VarDecl *Original;
3694 const VarDecl *PrivateCopy;
3695 const VarDecl *PrivateElemInit;
3696};
3697typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003698} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003699
Alexey Bataev9e034042015-05-05 04:05:12 +00003700static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003701createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003702 if (!Privates.empty()) {
3703 auto &C = CGM.getContext();
3704 // Build struct .kmp_privates_t. {
3705 // /* private vars */
3706 // };
3707 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3708 RD->startDefinition();
3709 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003710 auto *VD = Pair.second.Original;
3711 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003712 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003713 auto *FD = addFieldToRecordDecl(C, RD, Type);
3714 if (VD->hasAttrs()) {
3715 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3716 E(VD->getAttrs().end());
3717 I != E; ++I)
3718 FD->addAttr(*I);
3719 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003720 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003721 RD->completeDefinition();
3722 return RD;
3723 }
3724 return nullptr;
3725}
3726
Alexey Bataev9e034042015-05-05 04:05:12 +00003727static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003728createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3729 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003730 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003731 auto &C = CGM.getContext();
3732 // Build struct kmp_task_t {
3733 // void * shareds;
3734 // kmp_routine_entry_t routine;
3735 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003736 // kmp_cmplrdata_t data1;
3737 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003738 // For taskloops additional fields:
3739 // kmp_uint64 lb;
3740 // kmp_uint64 ub;
3741 // kmp_int64 st;
3742 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003743 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003744 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003745 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3746 UD->startDefinition();
3747 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3748 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3749 UD->completeDefinition();
3750 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003751 auto *RD = C.buildImplicitRecord("kmp_task_t");
3752 RD->startDefinition();
3753 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3754 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3755 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003756 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3757 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003758 if (isOpenMPTaskLoopDirective(Kind)) {
3759 QualType KmpUInt64Ty =
3760 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3761 QualType KmpInt64Ty =
3762 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3763 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3764 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3765 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3766 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003767 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003768 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003769 RD->completeDefinition();
3770 return RD;
3771}
3772
3773static RecordDecl *
3774createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003775 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003776 auto &C = CGM.getContext();
3777 // Build struct kmp_task_t_with_privates {
3778 // kmp_task_t task_data;
3779 // .kmp_privates_t. privates;
3780 // };
3781 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3782 RD->startDefinition();
3783 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003784 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3785 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3786 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003787 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003788 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003789}
3790
3791/// \brief Emit a proxy function which accepts kmp_task_t as the second
3792/// argument.
3793/// \code
3794/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003795/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003796/// For taskloops:
3797/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003798/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003799/// return 0;
3800/// }
3801/// \endcode
3802static llvm::Value *
3803emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003804 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3805 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003806 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003807 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3808 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003809 auto &C = CGM.getContext();
3810 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003811 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3812 ImplicitParamDecl::Other);
3813 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3814 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3815 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003816 Args.push_back(&GtidArg);
3817 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003818 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003819 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003820 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3821 auto *TaskEntry =
3822 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3823 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003824 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003825 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003826 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3827
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003828 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003829 // tt,
3830 // For taskloops:
3831 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3832 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003833 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003834 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003835 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3836 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3837 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003838 auto *KmpTaskTWithPrivatesQTyRD =
3839 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003840 LValue Base =
3841 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003842 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3843 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3844 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003845 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003846
3847 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3848 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003849 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003850 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003851 CGF.ConvertTypeForMem(SharedsPtrTy));
3852
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003853 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3854 llvm::Value *PrivatesParam;
3855 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3856 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3857 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003858 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003859 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003860 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003861
Alexey Bataev7292c292016-04-25 12:22:29 +00003862 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3863 TaskPrivatesMap,
3864 CGF.Builder
3865 .CreatePointerBitCastOrAddrSpaceCast(
3866 TDBase.getAddress(), CGF.VoidPtrTy)
3867 .getPointer()};
3868 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3869 std::end(CommonArgs));
3870 if (isOpenMPTaskLoopDirective(Kind)) {
3871 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3872 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3873 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3874 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3875 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3876 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3877 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3878 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3879 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3880 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3881 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3882 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003883 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3884 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3885 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003886 CallArgs.push_back(LBParam);
3887 CallArgs.push_back(UBParam);
3888 CallArgs.push_back(StParam);
3889 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003890 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003891 }
3892 CallArgs.push_back(SharedsParam);
3893
Alexey Bataev3c595a62017-08-14 15:01:03 +00003894 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3895 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003896 CGF.EmitStoreThroughLValue(
3897 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003898 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003899 CGF.FinishFunction();
3900 return TaskEntry;
3901}
3902
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003903static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3904 SourceLocation Loc,
3905 QualType KmpInt32Ty,
3906 QualType KmpTaskTWithPrivatesPtrQTy,
3907 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003908 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003909 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003910 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3911 ImplicitParamDecl::Other);
3912 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3913 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3914 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003915 Args.push_back(&GtidArg);
3916 Args.push_back(&TaskTypeArg);
3917 FunctionType::ExtInfo Info;
3918 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003919 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003920 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3921 auto *DestructorFn =
3922 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3923 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003924 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3925 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003926 CodeGenFunction CGF(CGM);
3927 CGF.disableDebugInfo();
3928 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3929 Args);
3930
Alexey Bataev31300ed2016-02-04 11:27:03 +00003931 LValue Base = CGF.EmitLoadOfPointerLValue(
3932 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3933 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003934 auto *KmpTaskTWithPrivatesQTyRD =
3935 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3936 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003937 Base = CGF.EmitLValueForField(Base, *FI);
3938 for (auto *Field :
3939 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3940 if (auto DtorKind = Field->getType().isDestructedType()) {
3941 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3942 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3943 }
3944 }
3945 CGF.FinishFunction();
3946 return DestructorFn;
3947}
3948
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003949/// \brief Emit a privates mapping function for correct handling of private and
3950/// firstprivate variables.
3951/// \code
3952/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3953/// **noalias priv1,..., <tyn> **noalias privn) {
3954/// *priv1 = &.privates.priv1;
3955/// ...;
3956/// *privn = &.privates.privn;
3957/// }
3958/// \endcode
3959static llvm::Value *
3960emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003961 ArrayRef<const Expr *> PrivateVars,
3962 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003963 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003964 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003965 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003966 auto &C = CGM.getContext();
3967 FunctionArgList Args;
3968 ImplicitParamDecl TaskPrivatesArg(
3969 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003970 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3971 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003972 Args.push_back(&TaskPrivatesArg);
3973 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3974 unsigned Counter = 1;
3975 for (auto *E: PrivateVars) {
3976 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003977 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3978 C.getPointerType(C.getPointerType(E->getType()))
3979 .withConst()
3980 .withRestrict(),
3981 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003982 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3983 PrivateVarsPos[VD] = Counter;
3984 ++Counter;
3985 }
3986 for (auto *E : FirstprivateVars) {
3987 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003988 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3989 C.getPointerType(C.getPointerType(E->getType()))
3990 .withConst()
3991 .withRestrict(),
3992 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003993 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3994 PrivateVarsPos[VD] = Counter;
3995 ++Counter;
3996 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003997 for (auto *E: LastprivateVars) {
3998 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003999 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4000 C.getPointerType(C.getPointerType(E->getType()))
4001 .withConst()
4002 .withRestrict(),
4003 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004004 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4005 PrivateVarsPos[VD] = Counter;
4006 ++Counter;
4007 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004008 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004009 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004010 auto *TaskPrivatesMapTy =
4011 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4012 auto *TaskPrivatesMap = llvm::Function::Create(
4013 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4014 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004015 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4016 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004017 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004018 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004019 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004020 CodeGenFunction CGF(CGM);
4021 CGF.disableDebugInfo();
4022 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4023 TaskPrivatesMapFnInfo, Args);
4024
4025 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004026 LValue Base = CGF.EmitLoadOfPointerLValue(
4027 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4028 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004029 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4030 Counter = 0;
4031 for (auto *Field : PrivatesQTyRD->fields()) {
4032 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4033 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004034 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004035 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4036 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004037 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004038 ++Counter;
4039 }
4040 CGF.FinishFunction();
4041 return TaskPrivatesMap;
4042}
4043
Alexey Bataev9e034042015-05-05 04:05:12 +00004044static int array_pod_sort_comparator(const PrivateDataTy *P1,
4045 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004046 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4047}
4048
Alexey Bataevf93095a2016-05-05 08:46:22 +00004049/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004050static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004051 const OMPExecutableDirective &D,
4052 Address KmpTaskSharedsPtr, LValue TDBase,
4053 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4054 QualType SharedsTy, QualType SharedsPtrTy,
4055 const OMPTaskDataTy &Data,
4056 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4057 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004058 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4059 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4060 LValue SrcBase;
4061 if (!Data.FirstprivateVars.empty()) {
4062 SrcBase = CGF.MakeAddrLValue(
4063 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4064 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4065 SharedsTy);
4066 }
4067 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4068 cast<CapturedStmt>(*D.getAssociatedStmt()));
4069 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4070 for (auto &&Pair : Privates) {
4071 auto *VD = Pair.second.PrivateCopy;
4072 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004073 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4074 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004075 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004076 if (auto *Elem = Pair.second.PrivateElemInit) {
4077 auto *OriginalVD = Pair.second.Original;
4078 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4079 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4080 SharedRefLValue = CGF.MakeAddrLValue(
4081 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004082 SharedRefLValue.getType(),
4083 LValueBaseInfo(AlignmentSource::Decl,
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004084 SharedRefLValue.getBaseInfo().getMayAlias()),
4085 CGF.CGM.getTBAAAccessInfo(SharedRefLValue.getType()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004086 QualType Type = OriginalVD->getType();
4087 if (Type->isArrayType()) {
4088 // Initialize firstprivate array.
4089 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4090 // Perform simple memcpy.
4091 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4092 SharedRefLValue.getAddress(), Type);
4093 } else {
4094 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004095 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004096 CGF.EmitOMPAggregateAssign(
4097 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4098 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4099 Address SrcElement) {
4100 // Clean up any temporaries needed by the initialization.
4101 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4102 InitScope.addPrivate(
4103 Elem, [SrcElement]() -> Address { return SrcElement; });
4104 (void)InitScope.Privatize();
4105 // Emit initialization for single element.
4106 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4107 CGF, &CapturesInfo);
4108 CGF.EmitAnyExprToMem(Init, DestElement,
4109 Init->getType().getQualifiers(),
4110 /*IsInitializer=*/false);
4111 });
4112 }
4113 } else {
4114 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4115 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4116 return SharedRefLValue.getAddress();
4117 });
4118 (void)InitScope.Privatize();
4119 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4120 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4121 /*capturedByInit=*/false);
4122 }
4123 } else
4124 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4125 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004126 ++FI;
4127 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004128}
4129
4130/// Check if duplication function is required for taskloops.
4131static bool checkInitIsRequired(CodeGenFunction &CGF,
4132 ArrayRef<PrivateDataTy> Privates) {
4133 bool InitRequired = false;
4134 for (auto &&Pair : Privates) {
4135 auto *VD = Pair.second.PrivateCopy;
4136 auto *Init = VD->getAnyInitializer();
4137 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4138 !CGF.isTrivialInitializer(Init));
4139 }
4140 return InitRequired;
4141}
4142
4143
4144/// Emit task_dup function (for initialization of
4145/// private/firstprivate/lastprivate vars and last_iter flag)
4146/// \code
4147/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4148/// lastpriv) {
4149/// // setup lastprivate flag
4150/// task_dst->last = lastpriv;
4151/// // could be constructor calls here...
4152/// }
4153/// \endcode
4154static llvm::Value *
4155emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4156 const OMPExecutableDirective &D,
4157 QualType KmpTaskTWithPrivatesPtrQTy,
4158 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4159 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4160 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4161 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4162 auto &C = CGM.getContext();
4163 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004164 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4165 KmpTaskTWithPrivatesPtrQTy,
4166 ImplicitParamDecl::Other);
4167 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4168 KmpTaskTWithPrivatesPtrQTy,
4169 ImplicitParamDecl::Other);
4170 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4171 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004172 Args.push_back(&DstArg);
4173 Args.push_back(&SrcArg);
4174 Args.push_back(&LastprivArg);
4175 auto &TaskDupFnInfo =
4176 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4177 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4178 auto *TaskDup =
4179 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4180 ".omp_task_dup.", &CGM.getModule());
4181 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4182 CodeGenFunction CGF(CGM);
4183 CGF.disableDebugInfo();
4184 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4185
4186 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4187 CGF.GetAddrOfLocalVar(&DstArg),
4188 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4189 // task_dst->liter = lastpriv;
4190 if (WithLastIter) {
4191 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4192 LValue Base = CGF.EmitLValueForField(
4193 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4194 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4195 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4196 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4197 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4198 }
4199
4200 // Emit initial values for private copies (if any).
4201 assert(!Privates.empty());
4202 Address KmpTaskSharedsPtr = Address::invalid();
4203 if (!Data.FirstprivateVars.empty()) {
4204 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4205 CGF.GetAddrOfLocalVar(&SrcArg),
4206 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4207 LValue Base = CGF.EmitLValueForField(
4208 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4209 KmpTaskSharedsPtr = Address(
4210 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4211 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4212 KmpTaskTShareds)),
4213 Loc),
4214 CGF.getNaturalTypeAlignment(SharedsTy));
4215 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004216 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4217 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004218 CGF.FinishFunction();
4219 return TaskDup;
4220}
4221
Alexey Bataev8a831592016-05-10 10:36:51 +00004222/// Checks if destructor function is required to be generated.
4223/// \return true if cleanups are required, false otherwise.
4224static bool
4225checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4226 bool NeedsCleanup = false;
4227 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4228 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4229 for (auto *FD : PrivateRD->fields()) {
4230 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4231 if (NeedsCleanup)
4232 break;
4233 }
4234 return NeedsCleanup;
4235}
4236
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004237CGOpenMPRuntime::TaskResultTy
4238CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4239 const OMPExecutableDirective &D,
4240 llvm::Value *TaskFunction, QualType SharedsTy,
4241 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004242 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004243 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004244 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004245 auto I = Data.PrivateCopies.begin();
4246 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004247 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4248 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004249 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004250 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4251 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004252 ++I;
4253 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004254 I = Data.FirstprivateCopies.begin();
4255 auto IElemInitRef = Data.FirstprivateInits.begin();
4256 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004257 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4258 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004259 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004260 PrivateHelpersTy(
4261 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4262 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004263 ++I;
4264 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004265 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004266 I = Data.LastprivateCopies.begin();
4267 for (auto *E : Data.LastprivateVars) {
4268 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4269 Privates.push_back(std::make_pair(
4270 C.getDeclAlign(VD),
4271 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4272 /*PrivateElemInit=*/nullptr)));
4273 ++I;
4274 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004275 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4276 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004277 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4278 // Build type kmp_routine_entry_t (if not built yet).
4279 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004280 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004281 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4282 if (SavedKmpTaskloopTQTy.isNull()) {
4283 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4284 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4285 }
4286 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004287 } else {
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004288 assert(D.getDirectiveKind() == OMPD_task &&
4289 "Expected taskloop or task directive");
4290 if (SavedKmpTaskTQTy.isNull()) {
4291 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4292 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4293 }
4294 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004295 }
4296 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004297 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004298 auto *KmpTaskTWithPrivatesQTyRD =
4299 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4300 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4301 QualType KmpTaskTWithPrivatesPtrQTy =
4302 C.getPointerType(KmpTaskTWithPrivatesQTy);
4303 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4304 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004305 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004306 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4307
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004308 // Emit initial values for private copies (if any).
4309 llvm::Value *TaskPrivatesMap = nullptr;
4310 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004311 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004312 if (!Privates.empty()) {
4313 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004314 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4315 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4316 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004317 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4318 TaskPrivatesMap, TaskPrivatesMapTy);
4319 } else {
4320 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4321 cast<llvm::PointerType>(TaskPrivatesMapTy));
4322 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004323 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4324 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004325 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004326 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4327 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4328 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004329
4330 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4331 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4332 // kmp_routine_entry_t *task_entry);
4333 // Task flags. Format is taken from
4334 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4335 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004336 enum {
4337 TiedFlag = 0x1,
4338 FinalFlag = 0x2,
4339 DestructorsFlag = 0x8,
4340 PriorityFlag = 0x20
4341 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004342 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004343 bool NeedsCleanup = false;
4344 if (!Privates.empty()) {
4345 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4346 if (NeedsCleanup)
4347 Flags = Flags | DestructorsFlag;
4348 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004349 if (Data.Priority.getInt())
4350 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004351 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004352 Data.Final.getPointer()
4353 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004354 CGF.Builder.getInt32(FinalFlag),
4355 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004356 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004357 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004358 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004359 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4360 getThreadID(CGF, Loc), TaskFlags,
4361 KmpTaskTWithPrivatesTySize, SharedsSize,
4362 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4363 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004364 auto *NewTask = CGF.EmitRuntimeCall(
4365 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004366 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4367 NewTask, KmpTaskTWithPrivatesPtrTy);
4368 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4369 KmpTaskTWithPrivatesQTy);
4370 LValue TDBase =
4371 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004372 // Fill the data in the resulting kmp_task_t record.
4373 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004374 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004375 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004376 KmpTaskSharedsPtr =
4377 Address(CGF.EmitLoadOfScalar(
4378 CGF.EmitLValueForField(
4379 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4380 KmpTaskTShareds)),
4381 Loc),
4382 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004383 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004384 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004385 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004386 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004387 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004388 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4389 SharedsTy, SharedsPtrTy, Data, Privates,
4390 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004391 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4392 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4393 Result.TaskDupFn = emitTaskDupFunction(
4394 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4395 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4396 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004397 }
4398 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004399 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4400 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004401 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004402 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4403 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4404 if (NeedsCleanup) {
4405 llvm::Value *DestructorFn = emitDestructorsFunction(
4406 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4407 KmpTaskTWithPrivatesQTy);
4408 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4409 LValue DestructorsLV = CGF.EmitLValueForField(
4410 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4411 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4412 DestructorFn, KmpRoutineEntryPtrTy),
4413 DestructorsLV);
4414 }
4415 // Set priority.
4416 if (Data.Priority.getInt()) {
4417 LValue Data2LV = CGF.EmitLValueForField(
4418 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4419 LValue PriorityLV = CGF.EmitLValueForField(
4420 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4421 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4422 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004423 Result.NewTask = NewTask;
4424 Result.TaskEntry = TaskEntry;
4425 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4426 Result.TDBase = TDBase;
4427 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4428 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004429}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004430
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004431void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4432 const OMPExecutableDirective &D,
4433 llvm::Value *TaskFunction,
4434 QualType SharedsTy, Address Shareds,
4435 const Expr *IfCond,
4436 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004437 if (!CGF.HaveInsertPoint())
4438 return;
4439
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004440 TaskResultTy Result =
4441 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4442 llvm::Value *NewTask = Result.NewTask;
4443 llvm::Value *TaskEntry = Result.TaskEntry;
4444 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4445 LValue TDBase = Result.TDBase;
4446 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004447 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004448 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004449 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004450 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004451 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004452 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004453 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004454 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4455 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004456 QualType FlagsTy =
4457 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004458 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4459 if (KmpDependInfoTy.isNull()) {
4460 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4461 KmpDependInfoRD->startDefinition();
4462 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4463 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4464 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4465 KmpDependInfoRD->completeDefinition();
4466 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004467 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004468 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004469 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004470 // Define type kmp_depend_info[<Dependences.size()>];
4471 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004472 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004473 ArrayType::Normal, /*IndexTypeQuals=*/0);
4474 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004475 DependenciesArray =
4476 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004477 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004478 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004479 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004480 llvm::Value *Size;
4481 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004482 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4483 LValue UpAddrLVal =
4484 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4485 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004486 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004487 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004488 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004489 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4490 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004491 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004492 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004493 auto Base = CGF.MakeAddrLValue(
4494 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004495 KmpDependInfoTy);
4496 // deps[i].base_addr = &<Dependences[i].second>;
4497 auto BaseAddrLVal = CGF.EmitLValueForField(
4498 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004499 CGF.EmitStoreOfScalar(
4500 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4501 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004502 // deps[i].len = sizeof(<Dependences[i].second>);
4503 auto LenLVal = CGF.EmitLValueForField(
4504 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4505 CGF.EmitStoreOfScalar(Size, LenLVal);
4506 // deps[i].flags = <Dependences[i].first>;
4507 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004508 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004509 case OMPC_DEPEND_in:
4510 DepKind = DepIn;
4511 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004512 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004513 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004514 case OMPC_DEPEND_inout:
4515 DepKind = DepInOut;
4516 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004517 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004518 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004519 case OMPC_DEPEND_unknown:
4520 llvm_unreachable("Unknown task dependence type");
4521 }
4522 auto FlagsLVal = CGF.EmitLValueForField(
4523 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4524 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4525 FlagsLVal);
4526 }
John McCall7f416cc2015-09-08 08:05:57 +00004527 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4528 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004529 CGF.VoidPtrTy);
4530 }
4531
Alexey Bataev62b63b12015-03-10 07:28:44 +00004532 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4533 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004534 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4535 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4536 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4537 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004538 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004539 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004540 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4541 llvm::Value *DepTaskArgs[7];
4542 if (NumDependencies) {
4543 DepTaskArgs[0] = UpLoc;
4544 DepTaskArgs[1] = ThreadID;
4545 DepTaskArgs[2] = NewTask;
4546 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4547 DepTaskArgs[4] = DependenciesArray.getPointer();
4548 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4549 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4550 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004551 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4552 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004553 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004554 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004555 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4556 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4557 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4558 }
John McCall7f416cc2015-09-08 08:05:57 +00004559 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004560 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004561 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004562 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004563 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004564 TaskArgs);
4565 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004566 // Check if parent region is untied and build return for untied task;
4567 if (auto *Region =
4568 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4569 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004570 };
John McCall7f416cc2015-09-08 08:05:57 +00004571
4572 llvm::Value *DepWaitTaskArgs[6];
4573 if (NumDependencies) {
4574 DepWaitTaskArgs[0] = UpLoc;
4575 DepWaitTaskArgs[1] = ThreadID;
4576 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4577 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4578 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4579 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4580 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004581 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004582 NumDependencies, &DepWaitTaskArgs,
4583 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004584 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004585 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4586 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4587 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4588 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4589 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004590 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004591 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004592 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004593 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004594 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4595 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004596 Action.Enter(CGF);
4597 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004598 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004599 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004600 };
4601
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004602 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4603 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004604 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4605 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004606 RegionCodeGenTy RCG(CodeGen);
4607 CommonActionTy Action(
4608 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4609 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4610 RCG.setAction(Action);
4611 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004612 };
John McCall7f416cc2015-09-08 08:05:57 +00004613
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004614 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004615 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004616 else {
4617 RegionCodeGenTy ThenRCG(ThenCodeGen);
4618 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004619 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004620}
4621
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004622void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4623 const OMPLoopDirective &D,
4624 llvm::Value *TaskFunction,
4625 QualType SharedsTy, Address Shareds,
4626 const Expr *IfCond,
4627 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004628 if (!CGF.HaveInsertPoint())
4629 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004630 TaskResultTy Result =
4631 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004632 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4633 // libcall.
4634 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4635 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4636 // sched, kmp_uint64 grainsize, void *task_dup);
4637 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4638 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4639 llvm::Value *IfVal;
4640 if (IfCond) {
4641 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4642 /*isSigned=*/true);
4643 } else
4644 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4645
4646 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004647 Result.TDBase,
4648 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004649 auto *LBVar =
4650 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4651 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4652 /*IsInitializer=*/true);
4653 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004654 Result.TDBase,
4655 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004656 auto *UBVar =
4657 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4658 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4659 /*IsInitializer=*/true);
4660 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004661 Result.TDBase,
4662 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004663 auto *StVar =
4664 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4665 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4666 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004667 // Store reductions address.
4668 LValue RedLVal = CGF.EmitLValueForField(
4669 Result.TDBase,
4670 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4671 if (Data.Reductions)
4672 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4673 else {
4674 CGF.EmitNullInitialization(RedLVal.getAddress(),
4675 CGF.getContext().VoidPtrTy);
4676 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004677 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004678 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004679 UpLoc,
4680 ThreadID,
4681 Result.NewTask,
4682 IfVal,
4683 LBLVal.getPointer(),
4684 UBLVal.getPointer(),
4685 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4686 llvm::ConstantInt::getNullValue(
4687 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004688 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004689 CGF.IntTy, Data.Schedule.getPointer()
4690 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004691 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004692 Data.Schedule.getPointer()
4693 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004694 /*isSigned=*/false)
4695 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004696 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4697 Result.TaskDupFn, CGF.VoidPtrTy)
4698 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004699 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4700}
4701
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004702/// \brief Emit reduction operation for each element of array (required for
4703/// array sections) LHS op = RHS.
4704/// \param Type Type of array.
4705/// \param LHSVar Variable on the left side of the reduction operation
4706/// (references element of array in original variable).
4707/// \param RHSVar Variable on the right side of the reduction operation
4708/// (references element of array in original variable).
4709/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4710/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004711static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004712 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4713 const VarDecl *RHSVar,
4714 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4715 const Expr *, const Expr *)> &RedOpGen,
4716 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4717 const Expr *UpExpr = nullptr) {
4718 // Perform element-by-element initialization.
4719 QualType ElementTy;
4720 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4721 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4722
4723 // Drill down to the base element type on both arrays.
4724 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4725 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4726
4727 auto RHSBegin = RHSAddr.getPointer();
4728 auto LHSBegin = LHSAddr.getPointer();
4729 // Cast from pointer to array type to pointer to single element.
4730 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4731 // The basic structure here is a while-do loop.
4732 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4733 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4734 auto IsEmpty =
4735 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4736 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4737
4738 // Enter the loop body, making that address the current address.
4739 auto EntryBB = CGF.Builder.GetInsertBlock();
4740 CGF.EmitBlock(BodyBB);
4741
4742 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4743
4744 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4745 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4746 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4747 Address RHSElementCurrent =
4748 Address(RHSElementPHI,
4749 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4750
4751 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4752 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4753 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4754 Address LHSElementCurrent =
4755 Address(LHSElementPHI,
4756 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4757
4758 // Emit copy.
4759 CodeGenFunction::OMPPrivateScope Scope(CGF);
4760 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4761 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4762 Scope.Privatize();
4763 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4764 Scope.ForceCleanup();
4765
4766 // Shift the address forward by one element.
4767 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4768 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4769 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4770 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4771 // Check whether we've reached the end.
4772 auto Done =
4773 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4774 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4775 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4776 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4777
4778 // Done.
4779 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4780}
4781
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004782/// Emit reduction combiner. If the combiner is a simple expression emit it as
4783/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4784/// UDR combiner function.
4785static void emitReductionCombiner(CodeGenFunction &CGF,
4786 const Expr *ReductionOp) {
4787 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4788 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4789 if (auto *DRE =
4790 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4791 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4792 std::pair<llvm::Function *, llvm::Function *> Reduction =
4793 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4794 RValue Func = RValue::get(Reduction.first);
4795 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4796 CGF.EmitIgnoredExpr(ReductionOp);
4797 return;
4798 }
4799 CGF.EmitIgnoredExpr(ReductionOp);
4800}
4801
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004802llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4803 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4804 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4805 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004806 auto &C = CGM.getContext();
4807
4808 // void reduction_func(void *LHSArg, void *RHSArg);
4809 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004810 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4811 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004812 Args.push_back(&LHSArg);
4813 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004814 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004815 auto *Fn = llvm::Function::Create(
4816 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4817 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004818 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004819 CodeGenFunction CGF(CGM);
4820 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4821
4822 // Dst = (void*[n])(LHSArg);
4823 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004824 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4825 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4826 ArgsType), CGF.getPointerAlign());
4827 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4828 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4829 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004830
4831 // ...
4832 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4833 // ...
4834 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004835 auto IPriv = Privates.begin();
4836 unsigned Idx = 0;
4837 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004838 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4839 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004840 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004841 });
4842 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4843 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004844 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004845 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004846 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004847 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004848 // Get array size and emit VLA type.
4849 ++Idx;
4850 Address Elem =
4851 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4852 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004853 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4854 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004855 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004856 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004857 CGF.EmitVariablyModifiedType(PrivTy);
4858 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004859 }
4860 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004861 IPriv = Privates.begin();
4862 auto ILHS = LHSExprs.begin();
4863 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004864 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004865 if ((*IPriv)->getType()->isArrayType()) {
4866 // Emit reduction for array section.
4867 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4868 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004869 EmitOMPAggregateReduction(
4870 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4871 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4872 emitReductionCombiner(CGF, E);
4873 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004874 } else
4875 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004876 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004877 ++IPriv;
4878 ++ILHS;
4879 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004880 }
4881 Scope.ForceCleanup();
4882 CGF.FinishFunction();
4883 return Fn;
4884}
4885
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004886void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4887 const Expr *ReductionOp,
4888 const Expr *PrivateRef,
4889 const DeclRefExpr *LHS,
4890 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004891 if (PrivateRef->getType()->isArrayType()) {
4892 // Emit reduction for array section.
4893 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4894 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4895 EmitOMPAggregateReduction(
4896 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4897 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4898 emitReductionCombiner(CGF, ReductionOp);
4899 });
4900 } else
4901 // Emit reduction for array subscript or single variable.
4902 emitReductionCombiner(CGF, ReductionOp);
4903}
4904
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004905void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004906 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004907 ArrayRef<const Expr *> LHSExprs,
4908 ArrayRef<const Expr *> RHSExprs,
4909 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004910 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004911 if (!CGF.HaveInsertPoint())
4912 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004913
4914 bool WithNowait = Options.WithNowait;
4915 bool SimpleReduction = Options.SimpleReduction;
4916
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004917 // Next code should be emitted for reduction:
4918 //
4919 // static kmp_critical_name lock = { 0 };
4920 //
4921 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4922 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4923 // ...
4924 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4925 // *(Type<n>-1*)rhs[<n>-1]);
4926 // }
4927 //
4928 // ...
4929 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4930 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4931 // RedList, reduce_func, &<lock>)) {
4932 // case 1:
4933 // ...
4934 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4935 // ...
4936 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4937 // break;
4938 // case 2:
4939 // ...
4940 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4941 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004942 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004943 // break;
4944 // default:;
4945 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004946 //
4947 // if SimpleReduction is true, only the next code is generated:
4948 // ...
4949 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4950 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004951
4952 auto &C = CGM.getContext();
4953
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004954 if (SimpleReduction) {
4955 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004956 auto IPriv = Privates.begin();
4957 auto ILHS = LHSExprs.begin();
4958 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004959 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004960 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4961 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004962 ++IPriv;
4963 ++ILHS;
4964 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004965 }
4966 return;
4967 }
4968
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004969 // 1. Build a list of reduction variables.
4970 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004971 auto Size = RHSExprs.size();
4972 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004973 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004974 // Reserve place for array size.
4975 ++Size;
4976 }
4977 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004978 QualType ReductionArrayTy =
4979 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4980 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004981 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004982 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004983 auto IPriv = Privates.begin();
4984 unsigned Idx = 0;
4985 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004986 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004987 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004988 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004989 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004990 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4991 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004992 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004993 // Store array size.
4994 ++Idx;
4995 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4996 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004997 llvm::Value *Size = CGF.Builder.CreateIntCast(
4998 CGF.getVLASize(
4999 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5000 .first,
5001 CGF.SizeTy, /*isSigned=*/false);
5002 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5003 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005004 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005005 }
5006
5007 // 2. Emit reduce_func().
5008 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005009 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5010 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005011
5012 // 3. Create static kmp_critical_name lock = { 0 };
5013 auto *Lock = getCriticalRegionLock(".reduction");
5014
5015 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5016 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005017 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005018 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005019 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005020 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5021 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005022 llvm::Value *Args[] = {
5023 IdentTLoc, // ident_t *<loc>
5024 ThreadId, // i32 <gtid>
5025 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5026 ReductionArrayTySize, // size_type sizeof(RedList)
5027 RL, // void *RedList
5028 ReductionFn, // void (*) (void *, void *) <reduce_func>
5029 Lock // kmp_critical_name *&<lock>
5030 };
5031 auto Res = CGF.EmitRuntimeCall(
5032 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5033 : OMPRTL__kmpc_reduce),
5034 Args);
5035
5036 // 5. Build switch(res)
5037 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5038 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5039
5040 // 6. Build case 1:
5041 // ...
5042 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5043 // ...
5044 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5045 // break;
5046 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5047 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5048 CGF.EmitBlock(Case1BB);
5049
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005050 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5051 llvm::Value *EndArgs[] = {
5052 IdentTLoc, // ident_t *<loc>
5053 ThreadId, // i32 <gtid>
5054 Lock // kmp_critical_name *&<lock>
5055 };
5056 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5057 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005058 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005059 auto IPriv = Privates.begin();
5060 auto ILHS = LHSExprs.begin();
5061 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005062 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005063 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5064 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005065 ++IPriv;
5066 ++ILHS;
5067 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005068 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005069 };
5070 RegionCodeGenTy RCG(CodeGen);
5071 CommonActionTy Action(
5072 nullptr, llvm::None,
5073 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5074 : OMPRTL__kmpc_end_reduce),
5075 EndArgs);
5076 RCG.setAction(Action);
5077 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005078
5079 CGF.EmitBranch(DefaultBB);
5080
5081 // 7. Build case 2:
5082 // ...
5083 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5084 // ...
5085 // break;
5086 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5087 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5088 CGF.EmitBlock(Case2BB);
5089
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005090 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5091 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005092 auto ILHS = LHSExprs.begin();
5093 auto IRHS = RHSExprs.begin();
5094 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005095 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005096 const Expr *XExpr = nullptr;
5097 const Expr *EExpr = nullptr;
5098 const Expr *UpExpr = nullptr;
5099 BinaryOperatorKind BO = BO_Comma;
5100 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5101 if (BO->getOpcode() == BO_Assign) {
5102 XExpr = BO->getLHS();
5103 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005104 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005105 }
5106 // Try to emit update expression as a simple atomic.
5107 auto *RHSExpr = UpExpr;
5108 if (RHSExpr) {
5109 // Analyze RHS part of the whole expression.
5110 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5111 RHSExpr->IgnoreParenImpCasts())) {
5112 // If this is a conditional operator, analyze its condition for
5113 // min/max reduction operator.
5114 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005115 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005116 if (auto *BORHS =
5117 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5118 EExpr = BORHS->getRHS();
5119 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005120 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005121 }
5122 if (XExpr) {
5123 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005124 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005125 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5126 const Expr *EExpr, const Expr *UpExpr) {
5127 LValue X = CGF.EmitLValue(XExpr);
5128 RValue E;
5129 if (EExpr)
5130 E = CGF.EmitAnyExpr(EExpr);
5131 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005132 X, E, BO, /*IsXLHSInRHSPart=*/true,
5133 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005134 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005135 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5136 PrivateScope.addPrivate(
5137 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5138 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5139 CGF.emitOMPSimpleStore(
5140 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5141 VD->getType().getNonReferenceType(), Loc);
5142 return LHSTemp;
5143 });
5144 (void)PrivateScope.Privatize();
5145 return CGF.EmitAnyExpr(UpExpr);
5146 });
5147 };
5148 if ((*IPriv)->getType()->isArrayType()) {
5149 // Emit atomic reduction for array section.
5150 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5151 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5152 AtomicRedGen, XExpr, EExpr, UpExpr);
5153 } else
5154 // Emit atomic reduction for array subscript or single variable.
5155 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5156 } else {
5157 // Emit as a critical region.
5158 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5159 const Expr *, const Expr *) {
5160 auto &RT = CGF.CGM.getOpenMPRuntime();
5161 RT.emitCriticalRegion(
5162 CGF, ".atomic_reduction",
5163 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5164 Action.Enter(CGF);
5165 emitReductionCombiner(CGF, E);
5166 },
5167 Loc);
5168 };
5169 if ((*IPriv)->getType()->isArrayType()) {
5170 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5171 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5172 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5173 CritRedGen);
5174 } else
5175 CritRedGen(CGF, nullptr, nullptr, nullptr);
5176 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005177 ++ILHS;
5178 ++IRHS;
5179 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005180 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005181 };
5182 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5183 if (!WithNowait) {
5184 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5185 llvm::Value *EndArgs[] = {
5186 IdentTLoc, // ident_t *<loc>
5187 ThreadId, // i32 <gtid>
5188 Lock // kmp_critical_name *&<lock>
5189 };
5190 CommonActionTy Action(nullptr, llvm::None,
5191 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5192 EndArgs);
5193 AtomicRCG.setAction(Action);
5194 AtomicRCG(CGF);
5195 } else
5196 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005197
5198 CGF.EmitBranch(DefaultBB);
5199 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5200}
5201
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005202/// Generates unique name for artificial threadprivate variables.
5203/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5204static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5205 unsigned N) {
5206 SmallString<256> Buffer;
5207 llvm::raw_svector_ostream Out(Buffer);
5208 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5209 return Out.str();
5210}
5211
5212/// Emits reduction initializer function:
5213/// \code
5214/// void @.red_init(void* %arg) {
5215/// %0 = bitcast void* %arg to <type>*
5216/// store <type> <init>, <type>* %0
5217/// ret void
5218/// }
5219/// \endcode
5220static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5221 SourceLocation Loc,
5222 ReductionCodeGen &RCG, unsigned N) {
5223 auto &C = CGM.getContext();
5224 FunctionArgList Args;
5225 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5226 Args.emplace_back(&Param);
5227 auto &FnInfo =
5228 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5229 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5230 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5231 ".red_init.", &CGM.getModule());
5232 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5233 CodeGenFunction CGF(CGM);
5234 CGF.disableDebugInfo();
5235 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5236 Address PrivateAddr = CGF.EmitLoadOfPointer(
5237 CGF.GetAddrOfLocalVar(&Param),
5238 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5239 llvm::Value *Size = nullptr;
5240 // If the size of the reduction item is non-constant, load it from global
5241 // threadprivate variable.
5242 if (RCG.getSizes(N).second) {
5243 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5244 CGF, CGM.getContext().getSizeType(),
5245 generateUniqueName("reduction_size", Loc, N));
5246 Size =
5247 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5248 CGM.getContext().getSizeType(), SourceLocation());
5249 }
5250 RCG.emitAggregateType(CGF, N, Size);
5251 LValue SharedLVal;
5252 // If initializer uses initializer from declare reduction construct, emit a
5253 // pointer to the address of the original reduction item (reuired by reduction
5254 // initializer)
5255 if (RCG.usesReductionInitializer(N)) {
5256 Address SharedAddr =
5257 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5258 CGF, CGM.getContext().VoidPtrTy,
5259 generateUniqueName("reduction", Loc, N));
5260 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5261 } else {
5262 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5263 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5264 CGM.getContext().VoidPtrTy);
5265 }
5266 // Emit the initializer:
5267 // %0 = bitcast void* %arg to <type>*
5268 // store <type> <init>, <type>* %0
5269 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5270 [](CodeGenFunction &) { return false; });
5271 CGF.FinishFunction();
5272 return Fn;
5273}
5274
5275/// Emits reduction combiner function:
5276/// \code
5277/// void @.red_comb(void* %arg0, void* %arg1) {
5278/// %lhs = bitcast void* %arg0 to <type>*
5279/// %rhs = bitcast void* %arg1 to <type>*
5280/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5281/// store <type> %2, <type>* %lhs
5282/// ret void
5283/// }
5284/// \endcode
5285static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5286 SourceLocation Loc,
5287 ReductionCodeGen &RCG, unsigned N,
5288 const Expr *ReductionOp,
5289 const Expr *LHS, const Expr *RHS,
5290 const Expr *PrivateRef) {
5291 auto &C = CGM.getContext();
5292 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5293 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5294 FunctionArgList Args;
5295 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5296 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5297 Args.emplace_back(&ParamInOut);
5298 Args.emplace_back(&ParamIn);
5299 auto &FnInfo =
5300 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5301 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5302 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5303 ".red_comb.", &CGM.getModule());
5304 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5305 CodeGenFunction CGF(CGM);
5306 CGF.disableDebugInfo();
5307 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5308 llvm::Value *Size = nullptr;
5309 // If the size of the reduction item is non-constant, load it from global
5310 // threadprivate variable.
5311 if (RCG.getSizes(N).second) {
5312 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5313 CGF, CGM.getContext().getSizeType(),
5314 generateUniqueName("reduction_size", Loc, N));
5315 Size =
5316 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5317 CGM.getContext().getSizeType(), SourceLocation());
5318 }
5319 RCG.emitAggregateType(CGF, N, Size);
5320 // Remap lhs and rhs variables to the addresses of the function arguments.
5321 // %lhs = bitcast void* %arg0 to <type>*
5322 // %rhs = bitcast void* %arg1 to <type>*
5323 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5324 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5325 // Pull out the pointer to the variable.
5326 Address PtrAddr = CGF.EmitLoadOfPointer(
5327 CGF.GetAddrOfLocalVar(&ParamInOut),
5328 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5329 return CGF.Builder.CreateElementBitCast(
5330 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5331 });
5332 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5333 // Pull out the pointer to the variable.
5334 Address PtrAddr = CGF.EmitLoadOfPointer(
5335 CGF.GetAddrOfLocalVar(&ParamIn),
5336 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5337 return CGF.Builder.CreateElementBitCast(
5338 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5339 });
5340 PrivateScope.Privatize();
5341 // Emit the combiner body:
5342 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5343 // store <type> %2, <type>* %lhs
5344 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5345 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5346 cast<DeclRefExpr>(RHS));
5347 CGF.FinishFunction();
5348 return Fn;
5349}
5350
5351/// Emits reduction finalizer function:
5352/// \code
5353/// void @.red_fini(void* %arg) {
5354/// %0 = bitcast void* %arg to <type>*
5355/// <destroy>(<type>* %0)
5356/// ret void
5357/// }
5358/// \endcode
5359static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5360 SourceLocation Loc,
5361 ReductionCodeGen &RCG, unsigned N) {
5362 if (!RCG.needCleanups(N))
5363 return nullptr;
5364 auto &C = CGM.getContext();
5365 FunctionArgList Args;
5366 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5367 Args.emplace_back(&Param);
5368 auto &FnInfo =
5369 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5370 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5371 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5372 ".red_fini.", &CGM.getModule());
5373 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5374 CodeGenFunction CGF(CGM);
5375 CGF.disableDebugInfo();
5376 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5377 Address PrivateAddr = CGF.EmitLoadOfPointer(
5378 CGF.GetAddrOfLocalVar(&Param),
5379 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5380 llvm::Value *Size = nullptr;
5381 // If the size of the reduction item is non-constant, load it from global
5382 // threadprivate variable.
5383 if (RCG.getSizes(N).second) {
5384 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5385 CGF, CGM.getContext().getSizeType(),
5386 generateUniqueName("reduction_size", Loc, N));
5387 Size =
5388 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5389 CGM.getContext().getSizeType(), SourceLocation());
5390 }
5391 RCG.emitAggregateType(CGF, N, Size);
5392 // Emit the finalizer body:
5393 // <destroy>(<type>* %0)
5394 RCG.emitCleanups(CGF, N, PrivateAddr);
5395 CGF.FinishFunction();
5396 return Fn;
5397}
5398
5399llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5400 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5401 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5402 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5403 return nullptr;
5404
5405 // Build typedef struct:
5406 // kmp_task_red_input {
5407 // void *reduce_shar; // shared reduction item
5408 // size_t reduce_size; // size of data item
5409 // void *reduce_init; // data initialization routine
5410 // void *reduce_fini; // data finalization routine
5411 // void *reduce_comb; // data combiner routine
5412 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5413 // } kmp_task_red_input_t;
5414 ASTContext &C = CGM.getContext();
5415 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5416 RD->startDefinition();
5417 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5418 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5419 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5420 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5421 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5422 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5423 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5424 RD->completeDefinition();
5425 QualType RDType = C.getRecordType(RD);
5426 unsigned Size = Data.ReductionVars.size();
5427 llvm::APInt ArraySize(/*numBits=*/64, Size);
5428 QualType ArrayRDType = C.getConstantArrayType(
5429 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5430 // kmp_task_red_input_t .rd_input.[Size];
5431 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5432 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5433 Data.ReductionOps);
5434 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5435 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5436 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5437 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5438 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5439 TaskRedInput.getPointer(), Idxs,
5440 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5441 ".rd_input.gep.");
5442 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5443 // ElemLVal.reduce_shar = &Shareds[Cnt];
5444 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5445 RCG.emitSharedLValue(CGF, Cnt);
5446 llvm::Value *CastedShared =
5447 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5448 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5449 RCG.emitAggregateType(CGF, Cnt);
5450 llvm::Value *SizeValInChars;
5451 llvm::Value *SizeVal;
5452 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5453 // We use delayed creation/initialization for VLAs, array sections and
5454 // custom reduction initializations. It is required because runtime does not
5455 // provide the way to pass the sizes of VLAs/array sections to
5456 // initializer/combiner/finalizer functions and does not pass the pointer to
5457 // original reduction item to the initializer. Instead threadprivate global
5458 // variables are used to store these values and use them in the functions.
5459 bool DelayedCreation = !!SizeVal;
5460 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5461 /*isSigned=*/false);
5462 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5463 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5464 // ElemLVal.reduce_init = init;
5465 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5466 llvm::Value *InitAddr =
5467 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5468 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5469 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5470 // ElemLVal.reduce_fini = fini;
5471 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5472 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5473 llvm::Value *FiniAddr = Fini
5474 ? CGF.EmitCastToVoidPtr(Fini)
5475 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5476 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5477 // ElemLVal.reduce_comb = comb;
5478 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5479 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5480 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5481 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5482 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5483 // ElemLVal.flags = 0;
5484 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5485 if (DelayedCreation) {
5486 CGF.EmitStoreOfScalar(
5487 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5488 FlagsLVal);
5489 } else
5490 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5491 }
5492 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5493 // *data);
5494 llvm::Value *Args[] = {
5495 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5496 /*isSigned=*/true),
5497 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5498 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5499 CGM.VoidPtrTy)};
5500 return CGF.EmitRuntimeCall(
5501 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5502}
5503
5504void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5505 SourceLocation Loc,
5506 ReductionCodeGen &RCG,
5507 unsigned N) {
5508 auto Sizes = RCG.getSizes(N);
5509 // Emit threadprivate global variable if the type is non-constant
5510 // (Sizes.second = nullptr).
5511 if (Sizes.second) {
5512 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5513 /*isSigned=*/false);
5514 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5515 CGF, CGM.getContext().getSizeType(),
5516 generateUniqueName("reduction_size", Loc, N));
5517 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5518 }
5519 // Store address of the original reduction item if custom initializer is used.
5520 if (RCG.usesReductionInitializer(N)) {
5521 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5522 CGF, CGM.getContext().VoidPtrTy,
5523 generateUniqueName("reduction", Loc, N));
5524 CGF.Builder.CreateStore(
5525 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5526 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5527 SharedAddr, /*IsVolatile=*/false);
5528 }
5529}
5530
5531Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5532 SourceLocation Loc,
5533 llvm::Value *ReductionsPtr,
5534 LValue SharedLVal) {
5535 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5536 // *d);
5537 llvm::Value *Args[] = {
5538 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5539 /*isSigned=*/true),
5540 ReductionsPtr,
5541 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5542 CGM.VoidPtrTy)};
5543 return Address(
5544 CGF.EmitRuntimeCall(
5545 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5546 SharedLVal.getAlignment());
5547}
5548
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005549void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5550 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005551 if (!CGF.HaveInsertPoint())
5552 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005553 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5554 // global_tid);
5555 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5556 // Ignore return result until untied tasks are supported.
5557 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005558 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5559 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005560}
5561
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005562void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005563 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005564 const RegionCodeGenTy &CodeGen,
5565 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005566 if (!CGF.HaveInsertPoint())
5567 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005568 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005569 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005570}
5571
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005572namespace {
5573enum RTCancelKind {
5574 CancelNoreq = 0,
5575 CancelParallel = 1,
5576 CancelLoop = 2,
5577 CancelSections = 3,
5578 CancelTaskgroup = 4
5579};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005580} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005581
5582static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5583 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005584 if (CancelRegion == OMPD_parallel)
5585 CancelKind = CancelParallel;
5586 else if (CancelRegion == OMPD_for)
5587 CancelKind = CancelLoop;
5588 else if (CancelRegion == OMPD_sections)
5589 CancelKind = CancelSections;
5590 else {
5591 assert(CancelRegion == OMPD_taskgroup);
5592 CancelKind = CancelTaskgroup;
5593 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005594 return CancelKind;
5595}
5596
5597void CGOpenMPRuntime::emitCancellationPointCall(
5598 CodeGenFunction &CGF, SourceLocation Loc,
5599 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005600 if (!CGF.HaveInsertPoint())
5601 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005602 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5603 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005604 if (auto *OMPRegionInfo =
5605 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005606 // For 'cancellation point taskgroup', the task region info may not have a
5607 // cancel. This may instead happen in another adjacent task.
5608 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005609 llvm::Value *Args[] = {
5610 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5611 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005612 // Ignore return result until untied tasks are supported.
5613 auto *Result = CGF.EmitRuntimeCall(
5614 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5615 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005616 // exit from construct;
5617 // }
5618 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5619 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5620 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5621 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5622 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005623 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005624 auto CancelDest =
5625 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005626 CGF.EmitBranchThroughCleanup(CancelDest);
5627 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5628 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005629 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005630}
5631
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005632void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005633 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005634 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005635 if (!CGF.HaveInsertPoint())
5636 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005637 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5638 // kmp_int32 cncl_kind);
5639 if (auto *OMPRegionInfo =
5640 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005641 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5642 PrePostActionTy &) {
5643 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005644 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005645 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005646 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5647 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005648 auto *Result = CGF.EmitRuntimeCall(
5649 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005650 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005651 // exit from construct;
5652 // }
5653 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5654 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5655 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5656 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5657 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005658 // exit from construct;
5659 auto CancelDest =
5660 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5661 CGF.EmitBranchThroughCleanup(CancelDest);
5662 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5663 };
5664 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005665 emitOMPIfClause(CGF, IfCond, ThenGen,
5666 [](CodeGenFunction &, PrePostActionTy &) {});
5667 else {
5668 RegionCodeGenTy ThenRCG(ThenGen);
5669 ThenRCG(CGF);
5670 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005671 }
5672}
Samuel Antaobed3c462015-10-02 16:14:20 +00005673
Samuel Antaoee8fb302016-01-06 13:42:12 +00005674/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005675/// consists of the file and device IDs as well as line number associated with
5676/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005677static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5678 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005679 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005680
5681 auto &SM = C.getSourceManager();
5682
5683 // The loc should be always valid and have a file ID (the user cannot use
5684 // #pragma directives in macros)
5685
5686 assert(Loc.isValid() && "Source location is expected to be always valid.");
5687 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5688
5689 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5690 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5691
5692 llvm::sys::fs::UniqueID ID;
5693 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5694 llvm_unreachable("Source file with target region no longer exists!");
5695
5696 DeviceID = ID.getDevice();
5697 FileID = ID.getFile();
5698 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005699}
5700
5701void CGOpenMPRuntime::emitTargetOutlinedFunction(
5702 const OMPExecutableDirective &D, StringRef ParentName,
5703 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005704 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005705 assert(!ParentName.empty() && "Invalid target region parent name!");
5706
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005707 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5708 IsOffloadEntry, CodeGen);
5709}
5710
5711void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5712 const OMPExecutableDirective &D, StringRef ParentName,
5713 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5714 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005715 // Create a unique name for the entry function using the source location
5716 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005717 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005718 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005719 //
5720 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005721 // mangled name of the function that encloses the target region and BB is the
5722 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005723
5724 unsigned DeviceID;
5725 unsigned FileID;
5726 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005727 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005728 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005729 SmallString<64> EntryFnName;
5730 {
5731 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005732 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5733 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005734 }
5735
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005736 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5737
Samuel Antaobed3c462015-10-02 16:14:20 +00005738 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005739 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005740 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005741
Samuel Antao6d004262016-06-16 18:39:34 +00005742 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005743
5744 // If this target outline function is not an offload entry, we don't need to
5745 // register it.
5746 if (!IsOffloadEntry)
5747 return;
5748
5749 // The target region ID is used by the runtime library to identify the current
5750 // target region, so it only has to be unique and not necessarily point to
5751 // anything. It could be the pointer to the outlined function that implements
5752 // the target region, but we aren't using that so that the compiler doesn't
5753 // need to keep that, and could therefore inline the host function if proven
5754 // worthwhile during optimization. In the other hand, if emitting code for the
5755 // device, the ID has to be the function address so that it can retrieved from
5756 // the offloading entry and launched by the runtime library. We also mark the
5757 // outlined function to have external linkage in case we are emitting code for
5758 // the device, because these functions will be entry points to the device.
5759
5760 if (CGM.getLangOpts().OpenMPIsDevice) {
5761 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5762 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5763 } else
5764 OutlinedFnID = new llvm::GlobalVariable(
5765 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5766 llvm::GlobalValue::PrivateLinkage,
5767 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5768
5769 // Register the information for the entry associated with this target region.
5770 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005771 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5772 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005773}
5774
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005775/// discard all CompoundStmts intervening between two constructs
5776static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5777 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5778 Body = CS->body_front();
5779
5780 return Body;
5781}
5782
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005783/// Emit the number of teams for a target directive. Inspect the num_teams
5784/// clause associated with a teams construct combined or closely nested
5785/// with the target directive.
5786///
5787/// Emit a team of size one for directives such as 'target parallel' that
5788/// have no associated teams construct.
5789///
5790/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005791static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005792emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5793 CodeGenFunction &CGF,
5794 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005795
5796 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5797 "teams directive expected to be "
5798 "emitted only for the host!");
5799
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005800 auto &Bld = CGF.Builder;
5801
5802 // If the target directive is combined with a teams directive:
5803 // Return the value in the num_teams clause, if any.
5804 // Otherwise, return 0 to denote the runtime default.
5805 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5806 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5807 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5808 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5809 /*IgnoreResultAssign*/ true);
5810 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5811 /*IsSigned=*/true);
5812 }
5813
5814 // The default value is 0.
5815 return Bld.getInt32(0);
5816 }
5817
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005818 // If the target directive is combined with a parallel directive but not a
5819 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005820 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5821 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005822
5823 // If the current target region has a teams region enclosed, we need to get
5824 // the number of teams to pass to the runtime function call. This is done
5825 // by generating the expression in a inlined region. This is required because
5826 // the expression is captured in the enclosing target environment when the
5827 // teams directive is not combined with target.
5828
5829 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5830
5831 // FIXME: Accommodate other combined directives with teams when they become
5832 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005833 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5834 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005835 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5836 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5837 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5838 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005839 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5840 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005841 }
5842
5843 // If we have an enclosed teams directive but no num_teams clause we use
5844 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005845 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005846 }
5847
5848 // No teams associated with the directive.
5849 return nullptr;
5850}
5851
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005852/// Emit the number of threads for a target directive. Inspect the
5853/// thread_limit clause associated with a teams construct combined or closely
5854/// nested with the target directive.
5855///
5856/// Emit the num_threads clause for directives such as 'target parallel' that
5857/// have no associated teams construct.
5858///
5859/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005860static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005861emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5862 CodeGenFunction &CGF,
5863 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005864
5865 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5866 "teams directive expected to be "
5867 "emitted only for the host!");
5868
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005869 auto &Bld = CGF.Builder;
5870
5871 //
5872 // If the target directive is combined with a teams directive:
5873 // Return the value in the thread_limit clause, if any.
5874 //
5875 // If the target directive is combined with a parallel directive:
5876 // Return the value in the num_threads clause, if any.
5877 //
5878 // If both clauses are set, select the minimum of the two.
5879 //
5880 // If neither teams or parallel combined directives set the number of threads
5881 // in a team, return 0 to denote the runtime default.
5882 //
5883 // If this is not a teams directive return nullptr.
5884
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005885 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5886 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005887 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5888 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005889 llvm::Value *ThreadLimitVal = nullptr;
5890
5891 if (const auto *ThreadLimitClause =
5892 D.getSingleClause<OMPThreadLimitClause>()) {
5893 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5894 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5895 /*IgnoreResultAssign*/ true);
5896 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5897 /*IsSigned=*/true);
5898 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005899
5900 if (const auto *NumThreadsClause =
5901 D.getSingleClause<OMPNumThreadsClause>()) {
5902 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5903 llvm::Value *NumThreads =
5904 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5905 /*IgnoreResultAssign*/ true);
5906 NumThreadsVal =
5907 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5908 }
5909
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005910 // Select the lesser of thread_limit and num_threads.
5911 if (NumThreadsVal)
5912 ThreadLimitVal = ThreadLimitVal
5913 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5914 ThreadLimitVal),
5915 NumThreadsVal, ThreadLimitVal)
5916 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005917
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005918 // Set default value passed to the runtime if either teams or a target
5919 // parallel type directive is found but no clause is specified.
5920 if (!ThreadLimitVal)
5921 ThreadLimitVal = DefaultThreadLimitVal;
5922
5923 return ThreadLimitVal;
5924 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005925
Samuel Antaob68e2db2016-03-03 16:20:23 +00005926 // If the current target region has a teams region enclosed, we need to get
5927 // the thread limit to pass to the runtime function call. This is done
5928 // by generating the expression in a inlined region. This is required because
5929 // the expression is captured in the enclosing target environment when the
5930 // teams directive is not combined with target.
5931
5932 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5933
5934 // FIXME: Accommodate other combined directives with teams when they become
5935 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005936 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5937 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005938 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5939 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5940 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5941 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5942 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5943 /*IsSigned=*/true);
5944 }
5945
5946 // If we have an enclosed teams directive but no thread_limit clause we use
5947 // the default value 0.
5948 return CGF.Builder.getInt32(0);
5949 }
5950
5951 // No teams associated with the directive.
5952 return nullptr;
5953}
5954
Samuel Antao86ace552016-04-27 22:40:57 +00005955namespace {
5956// \brief Utility to handle information from clauses associated with a given
5957// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5958// It provides a convenient interface to obtain the information and generate
5959// code for that information.
5960class MappableExprsHandler {
5961public:
5962 /// \brief Values for bit flags used to specify the mapping type for
5963 /// offloading.
5964 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005965 /// \brief Allocate memory on the device and move data from host to device.
5966 OMP_MAP_TO = 0x01,
5967 /// \brief Allocate memory on the device and move data from device to host.
5968 OMP_MAP_FROM = 0x02,
5969 /// \brief Always perform the requested mapping action on the element, even
5970 /// if it was already mapped before.
5971 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005972 /// \brief Delete the element from the device environment, ignoring the
5973 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005974 OMP_MAP_DELETE = 0x08,
5975 /// \brief The element being mapped is a pointer, therefore the pointee
5976 /// should be mapped as well.
5977 OMP_MAP_IS_PTR = 0x10,
5978 /// \brief This flags signals that an argument is the first one relating to
5979 /// a map/private clause expression. For some cases a single
5980 /// map/privatization results in multiple arguments passed to the runtime
5981 /// library.
5982 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005983 /// \brief Signal that the runtime library has to return the device pointer
5984 /// in the current position for the data being mapped.
5985 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005986 /// \brief This flag signals that the reference being passed is a pointer to
5987 /// private data.
5988 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005989 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005990 OMP_MAP_PRIVATE_VAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00005991 /// Implicit map
5992 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00005993 };
5994
Samuel Antaocc10b852016-07-28 14:23:26 +00005995 /// Class that associates information with a base pointer to be passed to the
5996 /// runtime library.
5997 class BasePointerInfo {
5998 /// The base pointer.
5999 llvm::Value *Ptr = nullptr;
6000 /// The base declaration that refers to this device pointer, or null if
6001 /// there is none.
6002 const ValueDecl *DevPtrDecl = nullptr;
6003
6004 public:
6005 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6006 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6007 llvm::Value *operator*() const { return Ptr; }
6008 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6009 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6010 };
6011
6012 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006013 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
6014 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
6015
6016private:
6017 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006018 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006019
6020 /// \brief Function the directive is being generated for.
6021 CodeGenFunction &CGF;
6022
Samuel Antaod486f842016-05-26 16:53:38 +00006023 /// \brief Set of all first private variables in the current directive.
6024 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6025
Samuel Antao6890b092016-07-28 14:25:09 +00006026 /// Map between device pointer declarations and their expression components.
6027 /// The key value for declarations in 'this' is null.
6028 llvm::DenseMap<
6029 const ValueDecl *,
6030 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6031 DevPointersMap;
6032
Samuel Antao86ace552016-04-27 22:40:57 +00006033 llvm::Value *getExprTypeSize(const Expr *E) const {
6034 auto ExprTy = E->getType().getCanonicalType();
6035
6036 // Reference types are ignored for mapping purposes.
6037 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6038 ExprTy = RefTy->getPointeeType().getCanonicalType();
6039
6040 // Given that an array section is considered a built-in type, we need to
6041 // do the calculation based on the length of the section instead of relying
6042 // on CGF.getTypeSize(E->getType()).
6043 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6044 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6045 OAE->getBase()->IgnoreParenImpCasts())
6046 .getCanonicalType();
6047
6048 // If there is no length associated with the expression, that means we
6049 // are using the whole length of the base.
6050 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6051 return CGF.getTypeSize(BaseTy);
6052
6053 llvm::Value *ElemSize;
6054 if (auto *PTy = BaseTy->getAs<PointerType>())
6055 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6056 else {
6057 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6058 assert(ATy && "Expecting array type if not a pointer type.");
6059 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6060 }
6061
6062 // If we don't have a length at this point, that is because we have an
6063 // array section with a single element.
6064 if (!OAE->getLength())
6065 return ElemSize;
6066
6067 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6068 LengthVal =
6069 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6070 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6071 }
6072 return CGF.getTypeSize(ExprTy);
6073 }
6074
6075 /// \brief Return the corresponding bits for a given map clause modifier. Add
6076 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006077 /// map as the first one of a series of maps that relate to the same map
6078 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006079 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6080 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006081 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006082 unsigned Bits = 0u;
6083 switch (MapType) {
6084 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006085 case OMPC_MAP_release:
6086 // alloc and release is the default behavior in the runtime library, i.e.
6087 // if we don't pass any bits alloc/release that is what the runtime is
6088 // going to do. Therefore, we don't need to signal anything for these two
6089 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006090 break;
6091 case OMPC_MAP_to:
6092 Bits = OMP_MAP_TO;
6093 break;
6094 case OMPC_MAP_from:
6095 Bits = OMP_MAP_FROM;
6096 break;
6097 case OMPC_MAP_tofrom:
6098 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6099 break;
6100 case OMPC_MAP_delete:
6101 Bits = OMP_MAP_DELETE;
6102 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006103 default:
6104 llvm_unreachable("Unexpected map type!");
6105 break;
6106 }
6107 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006108 Bits |= OMP_MAP_IS_PTR;
6109 if (AddIsFirstFlag)
6110 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006111 if (MapTypeModifier == OMPC_MAP_always)
6112 Bits |= OMP_MAP_ALWAYS;
6113 return Bits;
6114 }
6115
6116 /// \brief Return true if the provided expression is a final array section. A
6117 /// final array section, is one whose length can't be proved to be one.
6118 bool isFinalArraySectionExpression(const Expr *E) const {
6119 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6120
6121 // It is not an array section and therefore not a unity-size one.
6122 if (!OASE)
6123 return false;
6124
6125 // An array section with no colon always refer to a single element.
6126 if (OASE->getColonLoc().isInvalid())
6127 return false;
6128
6129 auto *Length = OASE->getLength();
6130
6131 // If we don't have a length we have to check if the array has size 1
6132 // for this dimension. Also, we should always expect a length if the
6133 // base type is pointer.
6134 if (!Length) {
6135 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6136 OASE->getBase()->IgnoreParenImpCasts())
6137 .getCanonicalType();
6138 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6139 return ATy->getSize().getSExtValue() != 1;
6140 // If we don't have a constant dimension length, we have to consider
6141 // the current section as having any size, so it is not necessarily
6142 // unitary. If it happen to be unity size, that's user fault.
6143 return true;
6144 }
6145
6146 // Check if the length evaluates to 1.
6147 llvm::APSInt ConstLength;
6148 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6149 return true; // Can have more that size 1.
6150
6151 return ConstLength.getSExtValue() != 1;
6152 }
6153
6154 /// \brief Generate the base pointers, section pointers, sizes and map type
6155 /// bits for the provided map type, map modifier, and expression components.
6156 /// \a IsFirstComponent should be set to true if the provided set of
6157 /// components is the first associated with a capture.
6158 void generateInfoForComponentList(
6159 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6160 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006161 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006162 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006163 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006164
6165 // The following summarizes what has to be generated for each map and the
6166 // types bellow. The generated information is expressed in this order:
6167 // base pointer, section pointer, size, flags
6168 // (to add to the ones that come from the map type and modifier).
6169 //
6170 // double d;
6171 // int i[100];
6172 // float *p;
6173 //
6174 // struct S1 {
6175 // int i;
6176 // float f[50];
6177 // }
6178 // struct S2 {
6179 // int i;
6180 // float f[50];
6181 // S1 s;
6182 // double *p;
6183 // struct S2 *ps;
6184 // }
6185 // S2 s;
6186 // S2 *ps;
6187 //
6188 // map(d)
6189 // &d, &d, sizeof(double), noflags
6190 //
6191 // map(i)
6192 // &i, &i, 100*sizeof(int), noflags
6193 //
6194 // map(i[1:23])
6195 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6196 //
6197 // map(p)
6198 // &p, &p, sizeof(float*), noflags
6199 //
6200 // map(p[1:24])
6201 // p, &p[1], 24*sizeof(float), noflags
6202 //
6203 // map(s)
6204 // &s, &s, sizeof(S2), noflags
6205 //
6206 // map(s.i)
6207 // &s, &(s.i), sizeof(int), noflags
6208 //
6209 // map(s.s.f)
6210 // &s, &(s.i.f), 50*sizeof(int), noflags
6211 //
6212 // map(s.p)
6213 // &s, &(s.p), sizeof(double*), noflags
6214 //
6215 // map(s.p[:22], s.a s.b)
6216 // &s, &(s.p), sizeof(double*), noflags
6217 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6218 //
6219 // map(s.ps)
6220 // &s, &(s.ps), sizeof(S2*), noflags
6221 //
6222 // map(s.ps->s.i)
6223 // &s, &(s.ps), sizeof(S2*), noflags
6224 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6225 //
6226 // map(s.ps->ps)
6227 // &s, &(s.ps), sizeof(S2*), noflags
6228 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6229 //
6230 // map(s.ps->ps->ps)
6231 // &s, &(s.ps), sizeof(S2*), noflags
6232 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6233 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6234 //
6235 // map(s.ps->ps->s.f[:22])
6236 // &s, &(s.ps), sizeof(S2*), noflags
6237 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6238 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6239 //
6240 // map(ps)
6241 // &ps, &ps, sizeof(S2*), noflags
6242 //
6243 // map(ps->i)
6244 // ps, &(ps->i), sizeof(int), noflags
6245 //
6246 // map(ps->s.f)
6247 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6248 //
6249 // map(ps->p)
6250 // ps, &(ps->p), sizeof(double*), noflags
6251 //
6252 // map(ps->p[:22])
6253 // ps, &(ps->p), sizeof(double*), noflags
6254 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6255 //
6256 // map(ps->ps)
6257 // ps, &(ps->ps), sizeof(S2*), noflags
6258 //
6259 // map(ps->ps->s.i)
6260 // ps, &(ps->ps), sizeof(S2*), noflags
6261 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6262 //
6263 // map(ps->ps->ps)
6264 // ps, &(ps->ps), sizeof(S2*), noflags
6265 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6266 //
6267 // map(ps->ps->ps->ps)
6268 // ps, &(ps->ps), sizeof(S2*), noflags
6269 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6270 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6271 //
6272 // map(ps->ps->ps->s.f[:22])
6273 // ps, &(ps->ps), sizeof(S2*), noflags
6274 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6275 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6276 // extra_flag
6277
6278 // Track if the map information being generated is the first for a capture.
6279 bool IsCaptureFirstInfo = IsFirstComponentList;
6280
6281 // Scan the components from the base to the complete expression.
6282 auto CI = Components.rbegin();
6283 auto CE = Components.rend();
6284 auto I = CI;
6285
6286 // Track if the map information being generated is the first for a list of
6287 // components.
6288 bool IsExpressionFirstInfo = true;
6289 llvm::Value *BP = nullptr;
6290
6291 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6292 // The base is the 'this' pointer. The content of the pointer is going
6293 // to be the base of the field being mapped.
6294 BP = CGF.EmitScalarExpr(ME->getBase());
6295 } else {
6296 // The base is the reference to the variable.
6297 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006298 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006299
6300 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006301 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006302 // reference. References are ignored for mapping purposes.
6303 QualType Ty =
6304 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6305 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6306 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006307 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006308 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006309 .getPointer();
6310
6311 // We do not need to generate individual map information for the
6312 // pointer, it can be associated with the combined storage.
6313 ++I;
6314 }
6315 }
6316
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006317 unsigned DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006318 for (; I != CE; ++I) {
6319 auto Next = std::next(I);
6320
6321 // We need to generate the addresses and sizes if this is the last
6322 // component, if the component is a pointer or if it is an array section
6323 // whose length can't be proved to be one. If this is a pointer, it
6324 // becomes the base address for the following components.
6325
6326 // A final array section, is one whose length can't be proved to be one.
6327 bool IsFinalArraySection =
6328 isFinalArraySectionExpression(I->getAssociatedExpression());
6329
6330 // Get information on whether the element is a pointer. Have to do a
6331 // special treatment for array sections given that they are built-in
6332 // types.
6333 const auto *OASE =
6334 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6335 bool IsPointer =
6336 (OASE &&
6337 OMPArraySectionExpr::getBaseOriginalType(OASE)
6338 .getCanonicalType()
6339 ->isAnyPointerType()) ||
6340 I->getAssociatedExpression()->getType()->isAnyPointerType();
6341
6342 if (Next == CE || IsPointer || IsFinalArraySection) {
6343
6344 // If this is not the last component, we expect the pointer to be
6345 // associated with an array expression or member expression.
6346 assert((Next == CE ||
6347 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6348 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6349 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6350 "Unexpected expression");
6351
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006352 llvm::Value *LB =
6353 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006354 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6355
Samuel Antao03a3cec2016-07-27 22:52:16 +00006356 // If we have a member expression and the current component is a
6357 // reference, we have to map the reference too. Whenever we have a
6358 // reference, the section that reference refers to is going to be a
6359 // load instruction from the storage assigned to the reference.
6360 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6361 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6362 auto *LI = cast<llvm::LoadInst>(LB);
6363 auto *RefAddr = LI->getPointerOperand();
6364
6365 BasePointers.push_back(BP);
6366 Pointers.push_back(RefAddr);
6367 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006368 Types.push_back(DefaultFlags |
6369 getMapTypeBits(
6370 /*MapType*/ OMPC_MAP_alloc,
6371 /*MapTypeModifier=*/OMPC_MAP_unknown,
6372 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006373 IsExpressionFirstInfo = false;
6374 IsCaptureFirstInfo = false;
6375 // The reference will be the next base address.
6376 BP = RefAddr;
6377 }
6378
6379 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006380 Pointers.push_back(LB);
6381 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006382
Samuel Antao6782e942016-05-26 16:48:10 +00006383 // We need to add a pointer flag for each map that comes from the
6384 // same expression except for the first one. We also need to signal
6385 // this map is the first one that relates with the current capture
6386 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006387 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6388 !IsExpressionFirstInfo,
6389 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006390
6391 // If we have a final array section, we are done with this expression.
6392 if (IsFinalArraySection)
6393 break;
6394
6395 // The pointer becomes the base for the next element.
6396 if (Next != CE)
6397 BP = LB;
6398
6399 IsExpressionFirstInfo = false;
6400 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006401 }
6402 }
6403 }
6404
Samuel Antaod486f842016-05-26 16:53:38 +00006405 /// \brief Return the adjusted map modifiers if the declaration a capture
6406 /// refers to appears in a first-private clause. This is expected to be used
6407 /// only with directives that start with 'target'.
6408 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6409 unsigned CurrentModifiers) {
6410 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6411
6412 // A first private variable captured by reference will use only the
6413 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6414 // declaration is known as first-private in this handler.
6415 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6416 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6417 MappableExprsHandler::OMP_MAP_TO;
6418
6419 // We didn't modify anything.
6420 return CurrentModifiers;
6421 }
6422
Samuel Antao86ace552016-04-27 22:40:57 +00006423public:
6424 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006425 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006426 // Extract firstprivate clause information.
6427 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6428 for (const auto *D : C->varlists())
6429 FirstPrivateDecls.insert(
6430 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006431 // Extract device pointer clause information.
6432 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6433 for (auto L : C->component_lists())
6434 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006435 }
Samuel Antao86ace552016-04-27 22:40:57 +00006436
6437 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006438 /// types for the extracted mappable expressions. Also, for each item that
6439 /// relates with a device pointer, a pair of the relevant declaration and
6440 /// index where it occurs is appended to the device pointers info array.
6441 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006442 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6443 MapFlagsArrayTy &Types) const {
6444 BasePointers.clear();
6445 Pointers.clear();
6446 Sizes.clear();
6447 Types.clear();
6448
6449 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006450 /// Kind that defines how a device pointer has to be returned.
6451 enum ReturnPointerKind {
6452 // Don't have to return any pointer.
6453 RPK_None,
6454 // Pointer is the base of the declaration.
6455 RPK_Base,
6456 // Pointer is a member of the base declaration - 'this'
6457 RPK_Member,
6458 // Pointer is a reference and a member of the base declaration - 'this'
6459 RPK_MemberReference,
6460 };
Samuel Antao86ace552016-04-27 22:40:57 +00006461 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006462 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6463 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6464 ReturnPointerKind ReturnDevicePointer = RPK_None;
6465 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006466
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006467 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006468 MapInfo(
6469 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6470 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006471 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006472 : Components(Components), MapType(MapType),
6473 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006474 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006475 };
6476
6477 // We have to process the component lists that relate with the same
6478 // declaration in a single chunk so that we can generate the map flags
6479 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006480 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006481
6482 // Helper function to fill the information map for the different supported
6483 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006484 auto &&InfoGen = [&Info](
6485 const ValueDecl *D,
6486 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6487 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006488 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006489 const ValueDecl *VD =
6490 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006491 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6492 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006493 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006494
Paul Robinson78fb1322016-08-01 22:12:46 +00006495 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006496 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006497 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006498 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006499 MapInfo::RPK_None, C->isImplicit());
6500 }
Paul Robinson15c84002016-07-29 20:46:16 +00006501 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006502 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006503 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006504 MapInfo::RPK_None, C->isImplicit());
6505 }
Paul Robinson15c84002016-07-29 20:46:16 +00006506 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006507 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006508 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006509 MapInfo::RPK_None, C->isImplicit());
6510 }
Samuel Antao86ace552016-04-27 22:40:57 +00006511
Samuel Antaocc10b852016-07-28 14:23:26 +00006512 // Look at the use_device_ptr clause information and mark the existing map
6513 // entries as such. If there is no map information for an entry in the
6514 // use_device_ptr list, we create one with map type 'alloc' and zero size
6515 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006516 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006517 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006518 for (auto L : C->component_lists()) {
6519 assert(!L.second.empty() && "Not expecting empty list of components!");
6520 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6521 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6522 auto *IE = L.second.back().getAssociatedExpression();
6523 // If the first component is a member expression, we have to look into
6524 // 'this', which maps to null in the map of map information. Otherwise
6525 // look directly for the information.
6526 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6527
6528 // We potentially have map information for this declaration already.
6529 // Look for the first set of components that refer to it.
6530 if (It != Info.end()) {
6531 auto CI = std::find_if(
6532 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6533 return MI.Components.back().getAssociatedDeclaration() == VD;
6534 });
6535 // If we found a map entry, signal that the pointer has to be returned
6536 // and move on to the next declaration.
6537 if (CI != It->second.end()) {
6538 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6539 ? (VD->getType()->isReferenceType()
6540 ? MapInfo::RPK_MemberReference
6541 : MapInfo::RPK_Member)
6542 : MapInfo::RPK_Base;
6543 continue;
6544 }
6545 }
6546
6547 // We didn't find any match in our map information - generate a zero
6548 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006549 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006550 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006551 this->CGF
6552 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006553 .getScalarVal();
6554 BasePointers.push_back({Ptr, VD});
6555 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006556 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006557 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6558 }
6559
Samuel Antao86ace552016-04-27 22:40:57 +00006560 for (auto &M : Info) {
6561 // We need to know when we generate information for the first component
6562 // associated with a capture, because the mapping flags depend on it.
6563 bool IsFirstComponentList = true;
6564 for (MapInfo &L : M.second) {
6565 assert(!L.Components.empty() &&
6566 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006567
6568 // Remember the current base pointer index.
6569 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006570 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006571 this->generateInfoForComponentList(
6572 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6573 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006574
6575 // If this entry relates with a device pointer, set the relevant
6576 // declaration and add the 'return pointer' flag.
6577 if (IsFirstComponentList &&
6578 L.ReturnDevicePointer != MapInfo::RPK_None) {
6579 // If the pointer is not the base of the map, we need to skip the
6580 // base. If it is a reference in a member field, we also need to skip
6581 // the map of the reference.
6582 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6583 ++CurrentBasePointersIdx;
6584 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6585 ++CurrentBasePointersIdx;
6586 }
6587 assert(BasePointers.size() > CurrentBasePointersIdx &&
6588 "Unexpected number of mapped base pointers.");
6589
6590 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6591 assert(RelevantVD &&
6592 "No relevant declaration related with device pointer??");
6593
6594 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6595 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6596 }
Samuel Antao86ace552016-04-27 22:40:57 +00006597 IsFirstComponentList = false;
6598 }
6599 }
6600 }
6601
6602 /// \brief Generate the base pointers, section pointers, sizes and map types
6603 /// associated to a given capture.
6604 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006605 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006606 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006607 MapValuesArrayTy &Pointers,
6608 MapValuesArrayTy &Sizes,
6609 MapFlagsArrayTy &Types) const {
6610 assert(!Cap->capturesVariableArrayType() &&
6611 "Not expecting to generate map info for a variable array type!");
6612
6613 BasePointers.clear();
6614 Pointers.clear();
6615 Sizes.clear();
6616 Types.clear();
6617
Samuel Antao6890b092016-07-28 14:25:09 +00006618 // We need to know when we generating information for the first component
6619 // associated with a capture, because the mapping flags depend on it.
6620 bool IsFirstComponentList = true;
6621
Samuel Antao86ace552016-04-27 22:40:57 +00006622 const ValueDecl *VD =
6623 Cap->capturesThis()
6624 ? nullptr
6625 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6626
Samuel Antao6890b092016-07-28 14:25:09 +00006627 // If this declaration appears in a is_device_ptr clause we just have to
6628 // pass the pointer by value. If it is a reference to a declaration, we just
6629 // pass its value, otherwise, if it is a member expression, we need to map
6630 // 'to' the field.
6631 if (!VD) {
6632 auto It = DevPointersMap.find(VD);
6633 if (It != DevPointersMap.end()) {
6634 for (auto L : It->second) {
6635 generateInfoForComponentList(
6636 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006637 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6638 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006639 IsFirstComponentList = false;
6640 }
6641 return;
6642 }
6643 } else if (DevPointersMap.count(VD)) {
6644 BasePointers.push_back({Arg, VD});
6645 Pointers.push_back(Arg);
6646 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6647 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6648 return;
6649 }
6650
Paul Robinson78fb1322016-08-01 22:12:46 +00006651 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006652 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006653 for (auto L : C->decl_component_lists(VD)) {
6654 assert(L.first == VD &&
6655 "We got information for the wrong declaration??");
6656 assert(!L.second.empty() &&
6657 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006658 generateInfoForComponentList(
6659 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6660 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006661 IsFirstComponentList = false;
6662 }
6663
6664 return;
6665 }
Samuel Antaod486f842016-05-26 16:53:38 +00006666
6667 /// \brief Generate the default map information for a given capture \a CI,
6668 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006669 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6670 const FieldDecl &RI, llvm::Value *CV,
6671 MapBaseValuesArrayTy &CurBasePointers,
6672 MapValuesArrayTy &CurPointers,
6673 MapValuesArrayTy &CurSizes,
6674 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006675
6676 // Do the default mapping.
6677 if (CI.capturesThis()) {
6678 CurBasePointers.push_back(CV);
6679 CurPointers.push_back(CV);
6680 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6681 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6682 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006683 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006684 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006685 CurBasePointers.push_back(CV);
6686 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006687 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006688 // We have to signal to the runtime captures passed by value that are
6689 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006690 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006691 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6692 } else {
6693 // Pointers are implicitly mapped with a zero size and no flags
6694 // (other than first map that is added for all implicit maps).
6695 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006696 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6697 }
6698 } else {
6699 assert(CI.capturesVariable() && "Expected captured reference.");
6700 CurBasePointers.push_back(CV);
6701 CurPointers.push_back(CV);
6702
6703 const ReferenceType *PtrTy =
6704 cast<ReferenceType>(RI.getType().getTypePtr());
6705 QualType ElementType = PtrTy->getPointeeType();
6706 CurSizes.push_back(CGF.getTypeSize(ElementType));
6707 // The default map type for a scalar/complex type is 'to' because by
6708 // default the value doesn't have to be retrieved. For an aggregate
6709 // type, the default is 'tofrom'.
6710 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006711 ? (OMP_MAP_TO | OMP_MAP_FROM)
6712 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006713
6714 // If we have a capture by reference we may need to add the private
6715 // pointer flag if the base declaration shows in some first-private
6716 // clause.
6717 CurMapTypes.back() =
6718 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6719 }
6720 // Every default map produces a single argument, so, it is always the
6721 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006722 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006723 }
Samuel Antao86ace552016-04-27 22:40:57 +00006724};
Samuel Antaodf158d52016-04-27 22:58:19 +00006725
6726enum OpenMPOffloadingReservedDeviceIDs {
6727 /// \brief Device ID if the device was not defined, runtime should get it
6728 /// from environment variables in the spec.
6729 OMP_DEVICEID_UNDEF = -1,
6730};
6731} // anonymous namespace
6732
6733/// \brief Emit the arrays used to pass the captures and map information to the
6734/// offloading runtime library. If there is no map or capture information,
6735/// return nullptr by reference.
6736static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006737emitOffloadingArrays(CodeGenFunction &CGF,
6738 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006739 MappableExprsHandler::MapValuesArrayTy &Pointers,
6740 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006741 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6742 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006743 auto &CGM = CGF.CGM;
6744 auto &Ctx = CGF.getContext();
6745
Samuel Antaocc10b852016-07-28 14:23:26 +00006746 // Reset the array information.
6747 Info.clearArrayInfo();
6748 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006749
Samuel Antaocc10b852016-07-28 14:23:26 +00006750 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006751 // Detect if we have any capture size requiring runtime evaluation of the
6752 // size so that a constant array could be eventually used.
6753 bool hasRuntimeEvaluationCaptureSize = false;
6754 for (auto *S : Sizes)
6755 if (!isa<llvm::Constant>(S)) {
6756 hasRuntimeEvaluationCaptureSize = true;
6757 break;
6758 }
6759
Samuel Antaocc10b852016-07-28 14:23:26 +00006760 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006761 QualType PointerArrayType =
6762 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6763 /*IndexTypeQuals=*/0);
6764
Samuel Antaocc10b852016-07-28 14:23:26 +00006765 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006766 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006767 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006768 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6769
6770 // If we don't have any VLA types or other types that require runtime
6771 // evaluation, we can use a constant array for the map sizes, otherwise we
6772 // need to fill up the arrays as we do for the pointers.
6773 if (hasRuntimeEvaluationCaptureSize) {
6774 QualType SizeArrayType = Ctx.getConstantArrayType(
6775 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6776 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006777 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006778 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6779 } else {
6780 // We expect all the sizes to be constant, so we collect them to create
6781 // a constant array.
6782 SmallVector<llvm::Constant *, 16> ConstSizes;
6783 for (auto S : Sizes)
6784 ConstSizes.push_back(cast<llvm::Constant>(S));
6785
6786 auto *SizesArrayInit = llvm::ConstantArray::get(
6787 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6788 auto *SizesArrayGbl = new llvm::GlobalVariable(
6789 CGM.getModule(), SizesArrayInit->getType(),
6790 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6791 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006792 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006793 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006794 }
6795
6796 // The map types are always constant so we don't need to generate code to
6797 // fill arrays. Instead, we create an array constant.
6798 llvm::Constant *MapTypesArrayInit =
6799 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6800 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6801 CGM.getModule(), MapTypesArrayInit->getType(),
6802 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6803 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006804 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006805 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006806
Samuel Antaocc10b852016-07-28 14:23:26 +00006807 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6808 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006809 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006810 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6811 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006812 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6813 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006814 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6815 CGF.Builder.CreateStore(BPVal, BPAddr);
6816
Samuel Antaocc10b852016-07-28 14:23:26 +00006817 if (Info.requiresDevicePointerInfo())
6818 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6819 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6820
Samuel Antaodf158d52016-04-27 22:58:19 +00006821 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006822 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006823 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6824 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006825 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6826 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006827 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6828 CGF.Builder.CreateStore(PVal, PAddr);
6829
6830 if (hasRuntimeEvaluationCaptureSize) {
6831 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006832 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6833 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006834 /*Idx0=*/0,
6835 /*Idx1=*/i);
6836 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6837 CGF.Builder.CreateStore(
6838 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6839 SAddr);
6840 }
6841 }
6842 }
6843}
6844/// \brief Emit the arguments to be passed to the runtime library based on the
6845/// arrays of pointers, sizes and map types.
6846static void emitOffloadingArraysArgument(
6847 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6848 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006849 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006850 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006851 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006852 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006853 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6854 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006855 /*Idx0=*/0, /*Idx1=*/0);
6856 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006857 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6858 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006859 /*Idx0=*/0,
6860 /*Idx1=*/0);
6861 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006862 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006863 /*Idx0=*/0, /*Idx1=*/0);
6864 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006865 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6866 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006867 /*Idx0=*/0,
6868 /*Idx1=*/0);
6869 } else {
6870 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6871 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6872 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6873 MapTypesArrayArg =
6874 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6875 }
Samuel Antao86ace552016-04-27 22:40:57 +00006876}
6877
Samuel Antaobed3c462015-10-02 16:14:20 +00006878void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6879 const OMPExecutableDirective &D,
6880 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006881 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006882 const Expr *IfCond, const Expr *Device,
6883 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006884 if (!CGF.HaveInsertPoint())
6885 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006886
Samuel Antaoee8fb302016-01-06 13:42:12 +00006887 assert(OutlinedFn && "Invalid outlined function!");
6888
Samuel Antao86ace552016-04-27 22:40:57 +00006889 // Fill up the arrays with all the captured variables.
6890 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006891 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006892 MappableExprsHandler::MapValuesArrayTy Pointers;
6893 MappableExprsHandler::MapValuesArrayTy Sizes;
6894 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006895
Samuel Antaocc10b852016-07-28 14:23:26 +00006896 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006897 MappableExprsHandler::MapValuesArrayTy CurPointers;
6898 MappableExprsHandler::MapValuesArrayTy CurSizes;
6899 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6900
Samuel Antaod486f842016-05-26 16:53:38 +00006901 // Get mappable expression information.
6902 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006903
6904 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6905 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006906 auto CV = CapturedVars.begin();
6907 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6908 CE = CS.capture_end();
6909 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00006910 CurBasePointers.clear();
6911 CurPointers.clear();
6912 CurSizes.clear();
6913 CurMapTypes.clear();
6914
6915 // VLA sizes are passed to the outlined region by copy and do not have map
6916 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006917 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006918 CurBasePointers.push_back(*CV);
6919 CurPointers.push_back(*CV);
6920 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006921 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006922 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6923 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006924 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006925 // If we have any information in the map clause, we use it, otherwise we
6926 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006927 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006928 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006929 if (CurBasePointers.empty())
6930 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6931 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006932 }
Samuel Antao86ace552016-04-27 22:40:57 +00006933 // We expect to have at least an element of information for this capture.
6934 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6935 assert(CurBasePointers.size() == CurPointers.size() &&
6936 CurBasePointers.size() == CurSizes.size() &&
6937 CurBasePointers.size() == CurMapTypes.size() &&
6938 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006939
Samuel Antao86ace552016-04-27 22:40:57 +00006940 // The kernel args are always the first elements of the base pointers
6941 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006942 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006943 // We need to append the results of this capture to what we already have.
6944 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6945 Pointers.append(CurPointers.begin(), CurPointers.end());
6946 Sizes.append(CurSizes.begin(), CurSizes.end());
6947 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006948 }
6949
Samuel Antaobed3c462015-10-02 16:14:20 +00006950 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00006951 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6952 OutlinedFn, OutlinedFnID, &D,
6953 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006954 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006955 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006956 TargetDataInfo Info;
6957 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6958 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6959 Info.PointersArray, Info.SizesArray,
6960 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006961
6962 // On top of the arrays that were filled up, the target offloading call
6963 // takes as arguments the device id as well as the host pointer. The host
6964 // pointer is used by the runtime library to identify the current target
6965 // region, so it only has to be unique and not necessarily point to
6966 // anything. It could be the pointer to the outlined function that
6967 // implements the target region, but we aren't using that so that the
6968 // compiler doesn't need to keep that, and could therefore inline the host
6969 // function if proven worthwhile during optimization.
6970
Samuel Antaoee8fb302016-01-06 13:42:12 +00006971 // From this point on, we need to have an ID of the target region defined.
6972 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006973
6974 // Emit device ID if any.
6975 llvm::Value *DeviceID;
6976 if (Device)
6977 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006978 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006979 else
6980 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6981
Samuel Antaodf158d52016-04-27 22:58:19 +00006982 // Emit the number of elements in the offloading arrays.
6983 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6984
Samuel Antaob68e2db2016-03-03 16:20:23 +00006985 // Return value of the runtime offloading call.
6986 llvm::Value *Return;
6987
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006988 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6989 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006990
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006991 // The target region is an outlined function launched by the runtime
6992 // via calls __tgt_target() or __tgt_target_teams().
6993 //
6994 // __tgt_target() launches a target region with one team and one thread,
6995 // executing a serial region. This master thread may in turn launch
6996 // more threads within its team upon encountering a parallel region,
6997 // however, no additional teams can be launched on the device.
6998 //
6999 // __tgt_target_teams() launches a target region with one or more teams,
7000 // each with one or more threads. This call is required for target
7001 // constructs such as:
7002 // 'target teams'
7003 // 'target' / 'teams'
7004 // 'target teams distribute parallel for'
7005 // 'target parallel'
7006 // and so on.
7007 //
7008 // Note that on the host and CPU targets, the runtime implementation of
7009 // these calls simply call the outlined function without forking threads.
7010 // The outlined functions themselves have runtime calls to
7011 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7012 // the compiler in emitTeamsCall() and emitParallelCall().
7013 //
7014 // In contrast, on the NVPTX target, the implementation of
7015 // __tgt_target_teams() launches a GPU kernel with the requested number
7016 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007017 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007018 // If we have NumTeams defined this means that we have an enclosed teams
7019 // region. Therefore we also expect to have NumThreads defined. These two
7020 // values should be defined in the presence of a teams directive,
7021 // regardless of having any clauses associated. If the user is using teams
7022 // but no clauses, these two values will be the default that should be
7023 // passed to the runtime library - a 32-bit integer with the value zero.
7024 assert(NumThreads && "Thread limit expression should be available along "
7025 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007026 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007027 DeviceID, OutlinedFnID,
7028 PointerNum, Info.BasePointersArray,
7029 Info.PointersArray, Info.SizesArray,
7030 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007031 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007032 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007033 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007034 } else {
7035 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007036 DeviceID, OutlinedFnID,
7037 PointerNum, Info.BasePointersArray,
7038 Info.PointersArray, Info.SizesArray,
7039 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007040 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007041 OffloadingArgs);
7042 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007043
Alexey Bataev2a007e02017-10-02 14:20:58 +00007044 // Check the error code and execute the host version if required.
7045 llvm::BasicBlock *OffloadFailedBlock =
7046 CGF.createBasicBlock("omp_offload.failed");
7047 llvm::BasicBlock *OffloadContBlock =
7048 CGF.createBasicBlock("omp_offload.cont");
7049 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7050 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7051
7052 CGF.EmitBlock(OffloadFailedBlock);
7053 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7054 CGF.EmitBranch(OffloadContBlock);
7055
7056 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007057 };
7058
Samuel Antaoee8fb302016-01-06 13:42:12 +00007059 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007060 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7061 PrePostActionTy &) {
7062 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7063 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007064 };
7065
7066 // If we have a target function ID it means that we need to support
7067 // offloading, otherwise, just execute on the host. We need to execute on host
7068 // regardless of the conditional in the if clause if, e.g., the user do not
7069 // specify target triples.
7070 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007071 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007072 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007073 else {
7074 RegionCodeGenTy ThenRCG(ThenGen);
7075 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007076 }
7077 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007078 RegionCodeGenTy ElseRCG(ElseGen);
7079 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007080 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007081}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007082
7083void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7084 StringRef ParentName) {
7085 if (!S)
7086 return;
7087
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007088 // Codegen OMP target directives that offload compute to the device.
7089 bool requiresDeviceCodegen =
7090 isa<OMPExecutableDirective>(S) &&
7091 isOpenMPTargetExecutionDirective(
7092 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007093
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007094 if (requiresDeviceCodegen) {
7095 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007096 unsigned DeviceID;
7097 unsigned FileID;
7098 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007099 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007100 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007101
7102 // Is this a target region that should not be emitted as an entry point? If
7103 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007104 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7105 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007106 return;
7107
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007108 switch (S->getStmtClass()) {
7109 case Stmt::OMPTargetDirectiveClass:
7110 CodeGenFunction::EmitOMPTargetDeviceFunction(
7111 CGM, ParentName, cast<OMPTargetDirective>(*S));
7112 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007113 case Stmt::OMPTargetParallelDirectiveClass:
7114 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7115 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7116 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007117 case Stmt::OMPTargetTeamsDirectiveClass:
7118 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7119 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7120 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007121 default:
7122 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7123 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007124 return;
7125 }
7126
7127 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007128 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007129 return;
7130
7131 scanForTargetRegionsFunctions(
7132 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7133 ParentName);
7134 return;
7135 }
7136
7137 // If this is a lambda function, look into its body.
7138 if (auto *L = dyn_cast<LambdaExpr>(S))
7139 S = L->getBody();
7140
7141 // Keep looking for target regions recursively.
7142 for (auto *II : S->children())
7143 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007144}
7145
7146bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7147 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7148
7149 // If emitting code for the host, we do not process FD here. Instead we do
7150 // the normal code generation.
7151 if (!CGM.getLangOpts().OpenMPIsDevice)
7152 return false;
7153
7154 // Try to detect target regions in the function.
7155 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7156
Samuel Antao4b75b872016-12-12 19:26:31 +00007157 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007158 // scanning. Therefore, we signal that this function is completely dealt
7159 // with.
7160 return true;
7161}
7162
7163bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7164 if (!CGM.getLangOpts().OpenMPIsDevice)
7165 return false;
7166
7167 // Check if there are Ctors/Dtors in this declaration and look for target
7168 // regions in it. We use the complete variant to produce the kernel name
7169 // mangling.
7170 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7171 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7172 for (auto *Ctor : RD->ctors()) {
7173 StringRef ParentName =
7174 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7175 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7176 }
7177 auto *Dtor = RD->getDestructor();
7178 if (Dtor) {
7179 StringRef ParentName =
7180 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7181 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7182 }
7183 }
7184
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007185 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007186 // implemented yet). Therefore we signal that GD was processed in this case.
7187 return true;
7188}
7189
7190bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7191 auto *VD = GD.getDecl();
7192 if (isa<FunctionDecl>(VD))
7193 return emitTargetFunctions(GD);
7194
7195 return emitTargetGlobalVariable(GD);
7196}
7197
7198llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7199 // If we have offloading in the current module, we need to emit the entries
7200 // now and register the offloading descriptor.
7201 createOffloadEntriesAndInfoMetadata();
7202
7203 // Create and register the offloading binary descriptors. This is the main
7204 // entity that captures all the information about offloading in the current
7205 // compilation unit.
7206 return createOffloadingBinaryDescriptorRegistration();
7207}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007208
7209void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7210 const OMPExecutableDirective &D,
7211 SourceLocation Loc,
7212 llvm::Value *OutlinedFn,
7213 ArrayRef<llvm::Value *> CapturedVars) {
7214 if (!CGF.HaveInsertPoint())
7215 return;
7216
7217 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7218 CodeGenFunction::RunCleanupsScope Scope(CGF);
7219
7220 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7221 llvm::Value *Args[] = {
7222 RTLoc,
7223 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7224 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7225 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7226 RealArgs.append(std::begin(Args), std::end(Args));
7227 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7228
7229 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7230 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7231}
7232
7233void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007234 const Expr *NumTeams,
7235 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007236 SourceLocation Loc) {
7237 if (!CGF.HaveInsertPoint())
7238 return;
7239
7240 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7241
Carlo Bertollic6872252016-04-04 15:55:02 +00007242 llvm::Value *NumTeamsVal =
7243 (NumTeams)
7244 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7245 CGF.CGM.Int32Ty, /* isSigned = */ true)
7246 : CGF.Builder.getInt32(0);
7247
7248 llvm::Value *ThreadLimitVal =
7249 (ThreadLimit)
7250 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7251 CGF.CGM.Int32Ty, /* isSigned = */ true)
7252 : CGF.Builder.getInt32(0);
7253
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007254 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007255 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7256 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007257 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7258 PushNumTeamsArgs);
7259}
Samuel Antaodf158d52016-04-27 22:58:19 +00007260
Samuel Antaocc10b852016-07-28 14:23:26 +00007261void CGOpenMPRuntime::emitTargetDataCalls(
7262 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7263 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007264 if (!CGF.HaveInsertPoint())
7265 return;
7266
Samuel Antaocc10b852016-07-28 14:23:26 +00007267 // Action used to replace the default codegen action and turn privatization
7268 // off.
7269 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007270
7271 // Generate the code for the opening of the data environment. Capture all the
7272 // arguments of the runtime call by reference because they are used in the
7273 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007274 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7275 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007276 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007277 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007278 MappableExprsHandler::MapValuesArrayTy Pointers;
7279 MappableExprsHandler::MapValuesArrayTy Sizes;
7280 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7281
7282 // Get map clause information.
7283 MappableExprsHandler MCHandler(D, CGF);
7284 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007285
7286 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007287 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007288
7289 llvm::Value *BasePointersArrayArg = nullptr;
7290 llvm::Value *PointersArrayArg = nullptr;
7291 llvm::Value *SizesArrayArg = nullptr;
7292 llvm::Value *MapTypesArrayArg = nullptr;
7293 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007294 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007295
7296 // Emit device ID if any.
7297 llvm::Value *DeviceID = nullptr;
7298 if (Device)
7299 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7300 CGF.Int32Ty, /*isSigned=*/true);
7301 else
7302 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7303
7304 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007305 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007306
7307 llvm::Value *OffloadingArgs[] = {
7308 DeviceID, PointerNum, BasePointersArrayArg,
7309 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7310 auto &RT = CGF.CGM.getOpenMPRuntime();
7311 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7312 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007313
7314 // If device pointer privatization is required, emit the body of the region
7315 // here. It will have to be duplicated: with and without privatization.
7316 if (!Info.CaptureDeviceAddrMap.empty())
7317 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007318 };
7319
7320 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007321 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007322 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007323
7324 llvm::Value *BasePointersArrayArg = nullptr;
7325 llvm::Value *PointersArrayArg = nullptr;
7326 llvm::Value *SizesArrayArg = nullptr;
7327 llvm::Value *MapTypesArrayArg = nullptr;
7328 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007329 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007330
7331 // Emit device ID if any.
7332 llvm::Value *DeviceID = nullptr;
7333 if (Device)
7334 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7335 CGF.Int32Ty, /*isSigned=*/true);
7336 else
7337 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7338
7339 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007340 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007341
7342 llvm::Value *OffloadingArgs[] = {
7343 DeviceID, PointerNum, BasePointersArrayArg,
7344 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7345 auto &RT = CGF.CGM.getOpenMPRuntime();
7346 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7347 OffloadingArgs);
7348 };
7349
Samuel Antaocc10b852016-07-28 14:23:26 +00007350 // If we need device pointer privatization, we need to emit the body of the
7351 // region with no privatization in the 'else' branch of the conditional.
7352 // Otherwise, we don't have to do anything.
7353 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7354 PrePostActionTy &) {
7355 if (!Info.CaptureDeviceAddrMap.empty()) {
7356 CodeGen.setAction(NoPrivAction);
7357 CodeGen(CGF);
7358 }
7359 };
7360
7361 // We don't have to do anything to close the region if the if clause evaluates
7362 // to false.
7363 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007364
7365 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007366 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007367 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007368 RegionCodeGenTy RCG(BeginThenGen);
7369 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007370 }
7371
Samuel Antaocc10b852016-07-28 14:23:26 +00007372 // If we don't require privatization of device pointers, we emit the body in
7373 // between the runtime calls. This avoids duplicating the body code.
7374 if (Info.CaptureDeviceAddrMap.empty()) {
7375 CodeGen.setAction(NoPrivAction);
7376 CodeGen(CGF);
7377 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007378
7379 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007380 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007381 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007382 RegionCodeGenTy RCG(EndThenGen);
7383 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007384 }
7385}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007386
Samuel Antao8d2d7302016-05-26 18:30:22 +00007387void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007388 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7389 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007390 if (!CGF.HaveInsertPoint())
7391 return;
7392
Samuel Antao8dd66282016-04-27 23:14:30 +00007393 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007394 isa<OMPTargetExitDataDirective>(D) ||
7395 isa<OMPTargetUpdateDirective>(D)) &&
7396 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007397
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007398 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007399 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007400 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007401 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007402 MappableExprsHandler::MapValuesArrayTy Pointers;
7403 MappableExprsHandler::MapValuesArrayTy Sizes;
7404 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7405
7406 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007407 MappableExprsHandler MEHandler(D, CGF);
7408 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007409
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007410 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007411 TargetDataInfo Info;
7412 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7413 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7414 Info.PointersArray, Info.SizesArray,
7415 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007416
7417 // Emit device ID if any.
7418 llvm::Value *DeviceID = nullptr;
7419 if (Device)
7420 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7421 CGF.Int32Ty, /*isSigned=*/true);
7422 else
7423 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7424
7425 // Emit the number of elements in the offloading arrays.
7426 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7427
7428 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007429 DeviceID, PointerNum, Info.BasePointersArray,
7430 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007431
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007432 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007433 // Select the right runtime function call for each expected standalone
7434 // directive.
7435 OpenMPRTLFunction RTLFn;
7436 switch (D.getDirectiveKind()) {
7437 default:
7438 llvm_unreachable("Unexpected standalone target data directive.");
7439 break;
7440 case OMPD_target_enter_data:
7441 RTLFn = OMPRTL__tgt_target_data_begin;
7442 break;
7443 case OMPD_target_exit_data:
7444 RTLFn = OMPRTL__tgt_target_data_end;
7445 break;
7446 case OMPD_target_update:
7447 RTLFn = OMPRTL__tgt_target_data_update;
7448 break;
7449 }
7450 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007451 };
7452
7453 // In the event we get an if clause, we don't have to take any action on the
7454 // else side.
7455 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7456
7457 if (IfCond) {
7458 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7459 } else {
7460 RegionCodeGenTy ThenGenRCG(ThenGen);
7461 ThenGenRCG(CGF);
7462 }
7463}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007464
7465namespace {
7466 /// Kind of parameter in a function with 'declare simd' directive.
7467 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7468 /// Attribute set of the parameter.
7469 struct ParamAttrTy {
7470 ParamKindTy Kind = Vector;
7471 llvm::APSInt StrideOrArg;
7472 llvm::APSInt Alignment;
7473 };
7474} // namespace
7475
7476static unsigned evaluateCDTSize(const FunctionDecl *FD,
7477 ArrayRef<ParamAttrTy> ParamAttrs) {
7478 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7479 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7480 // of that clause. The VLEN value must be power of 2.
7481 // In other case the notion of the function`s "characteristic data type" (CDT)
7482 // is used to compute the vector length.
7483 // CDT is defined in the following order:
7484 // a) For non-void function, the CDT is the return type.
7485 // b) If the function has any non-uniform, non-linear parameters, then the
7486 // CDT is the type of the first such parameter.
7487 // c) If the CDT determined by a) or b) above is struct, union, or class
7488 // type which is pass-by-value (except for the type that maps to the
7489 // built-in complex data type), the characteristic data type is int.
7490 // d) If none of the above three cases is applicable, the CDT is int.
7491 // The VLEN is then determined based on the CDT and the size of vector
7492 // register of that ISA for which current vector version is generated. The
7493 // VLEN is computed using the formula below:
7494 // VLEN = sizeof(vector_register) / sizeof(CDT),
7495 // where vector register size specified in section 3.2.1 Registers and the
7496 // Stack Frame of original AMD64 ABI document.
7497 QualType RetType = FD->getReturnType();
7498 if (RetType.isNull())
7499 return 0;
7500 ASTContext &C = FD->getASTContext();
7501 QualType CDT;
7502 if (!RetType.isNull() && !RetType->isVoidType())
7503 CDT = RetType;
7504 else {
7505 unsigned Offset = 0;
7506 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7507 if (ParamAttrs[Offset].Kind == Vector)
7508 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7509 ++Offset;
7510 }
7511 if (CDT.isNull()) {
7512 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7513 if (ParamAttrs[I + Offset].Kind == Vector) {
7514 CDT = FD->getParamDecl(I)->getType();
7515 break;
7516 }
7517 }
7518 }
7519 }
7520 if (CDT.isNull())
7521 CDT = C.IntTy;
7522 CDT = CDT->getCanonicalTypeUnqualified();
7523 if (CDT->isRecordType() || CDT->isUnionType())
7524 CDT = C.IntTy;
7525 return C.getTypeSize(CDT);
7526}
7527
7528static void
7529emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007530 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007531 ArrayRef<ParamAttrTy> ParamAttrs,
7532 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7533 struct ISADataTy {
7534 char ISA;
7535 unsigned VecRegSize;
7536 };
7537 ISADataTy ISAData[] = {
7538 {
7539 'b', 128
7540 }, // SSE
7541 {
7542 'c', 256
7543 }, // AVX
7544 {
7545 'd', 256
7546 }, // AVX2
7547 {
7548 'e', 512
7549 }, // AVX512
7550 };
7551 llvm::SmallVector<char, 2> Masked;
7552 switch (State) {
7553 case OMPDeclareSimdDeclAttr::BS_Undefined:
7554 Masked.push_back('N');
7555 Masked.push_back('M');
7556 break;
7557 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7558 Masked.push_back('N');
7559 break;
7560 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7561 Masked.push_back('M');
7562 break;
7563 }
7564 for (auto Mask : Masked) {
7565 for (auto &Data : ISAData) {
7566 SmallString<256> Buffer;
7567 llvm::raw_svector_ostream Out(Buffer);
7568 Out << "_ZGV" << Data.ISA << Mask;
7569 if (!VLENVal) {
7570 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7571 evaluateCDTSize(FD, ParamAttrs));
7572 } else
7573 Out << VLENVal;
7574 for (auto &ParamAttr : ParamAttrs) {
7575 switch (ParamAttr.Kind){
7576 case LinearWithVarStride:
7577 Out << 's' << ParamAttr.StrideOrArg;
7578 break;
7579 case Linear:
7580 Out << 'l';
7581 if (!!ParamAttr.StrideOrArg)
7582 Out << ParamAttr.StrideOrArg;
7583 break;
7584 case Uniform:
7585 Out << 'u';
7586 break;
7587 case Vector:
7588 Out << 'v';
7589 break;
7590 }
7591 if (!!ParamAttr.Alignment)
7592 Out << 'a' << ParamAttr.Alignment;
7593 }
7594 Out << '_' << Fn->getName();
7595 Fn->addFnAttr(Out.str());
7596 }
7597 }
7598}
7599
7600void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7601 llvm::Function *Fn) {
7602 ASTContext &C = CGM.getContext();
7603 FD = FD->getCanonicalDecl();
7604 // Map params to their positions in function decl.
7605 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7606 if (isa<CXXMethodDecl>(FD))
7607 ParamPositions.insert({FD, 0});
7608 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007609 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007610 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7611 ++ParamPos;
7612 }
7613 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7614 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7615 // Mark uniform parameters.
7616 for (auto *E : Attr->uniforms()) {
7617 E = E->IgnoreParenImpCasts();
7618 unsigned Pos;
7619 if (isa<CXXThisExpr>(E))
7620 Pos = ParamPositions[FD];
7621 else {
7622 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7623 ->getCanonicalDecl();
7624 Pos = ParamPositions[PVD];
7625 }
7626 ParamAttrs[Pos].Kind = Uniform;
7627 }
7628 // Get alignment info.
7629 auto NI = Attr->alignments_begin();
7630 for (auto *E : Attr->aligneds()) {
7631 E = E->IgnoreParenImpCasts();
7632 unsigned Pos;
7633 QualType ParmTy;
7634 if (isa<CXXThisExpr>(E)) {
7635 Pos = ParamPositions[FD];
7636 ParmTy = E->getType();
7637 } else {
7638 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7639 ->getCanonicalDecl();
7640 Pos = ParamPositions[PVD];
7641 ParmTy = PVD->getType();
7642 }
7643 ParamAttrs[Pos].Alignment =
7644 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7645 : llvm::APSInt::getUnsigned(
7646 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7647 .getQuantity());
7648 ++NI;
7649 }
7650 // Mark linear parameters.
7651 auto SI = Attr->steps_begin();
7652 auto MI = Attr->modifiers_begin();
7653 for (auto *E : Attr->linears()) {
7654 E = E->IgnoreParenImpCasts();
7655 unsigned Pos;
7656 if (isa<CXXThisExpr>(E))
7657 Pos = ParamPositions[FD];
7658 else {
7659 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7660 ->getCanonicalDecl();
7661 Pos = ParamPositions[PVD];
7662 }
7663 auto &ParamAttr = ParamAttrs[Pos];
7664 ParamAttr.Kind = Linear;
7665 if (*SI) {
7666 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7667 Expr::SE_AllowSideEffects)) {
7668 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7669 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7670 ParamAttr.Kind = LinearWithVarStride;
7671 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7672 ParamPositions[StridePVD->getCanonicalDecl()]);
7673 }
7674 }
7675 }
7676 }
7677 ++SI;
7678 ++MI;
7679 }
7680 llvm::APSInt VLENVal;
7681 if (const Expr *VLEN = Attr->getSimdlen())
7682 VLENVal = VLEN->EvaluateKnownConstInt(C);
7683 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7684 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7685 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7686 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7687 }
7688}
Alexey Bataev8b427062016-05-25 12:36:08 +00007689
7690namespace {
7691/// Cleanup action for doacross support.
7692class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7693public:
7694 static const int DoacrossFinArgs = 2;
7695
7696private:
7697 llvm::Value *RTLFn;
7698 llvm::Value *Args[DoacrossFinArgs];
7699
7700public:
7701 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7702 : RTLFn(RTLFn) {
7703 assert(CallArgs.size() == DoacrossFinArgs);
7704 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7705 }
7706 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7707 if (!CGF.HaveInsertPoint())
7708 return;
7709 CGF.EmitRuntimeCall(RTLFn, Args);
7710 }
7711};
7712} // namespace
7713
7714void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7715 const OMPLoopDirective &D) {
7716 if (!CGF.HaveInsertPoint())
7717 return;
7718
7719 ASTContext &C = CGM.getContext();
7720 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7721 RecordDecl *RD;
7722 if (KmpDimTy.isNull()) {
7723 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7724 // kmp_int64 lo; // lower
7725 // kmp_int64 up; // upper
7726 // kmp_int64 st; // stride
7727 // };
7728 RD = C.buildImplicitRecord("kmp_dim");
7729 RD->startDefinition();
7730 addFieldToRecordDecl(C, RD, Int64Ty);
7731 addFieldToRecordDecl(C, RD, Int64Ty);
7732 addFieldToRecordDecl(C, RD, Int64Ty);
7733 RD->completeDefinition();
7734 KmpDimTy = C.getRecordType(RD);
7735 } else
7736 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7737
7738 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7739 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7740 enum { LowerFD = 0, UpperFD, StrideFD };
7741 // Fill dims with data.
7742 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7743 // dims.upper = num_iterations;
7744 LValue UpperLVal =
7745 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7746 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7747 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7748 Int64Ty, D.getNumIterations()->getExprLoc());
7749 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7750 // dims.stride = 1;
7751 LValue StrideLVal =
7752 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7753 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7754 StrideLVal);
7755
7756 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7757 // kmp_int32 num_dims, struct kmp_dim * dims);
7758 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7759 getThreadID(CGF, D.getLocStart()),
7760 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7761 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7762 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7763
7764 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7765 CGF.EmitRuntimeCall(RTLFn, Args);
7766 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7767 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7768 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7769 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7770 llvm::makeArrayRef(FiniArgs));
7771}
7772
7773void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7774 const OMPDependClause *C) {
7775 QualType Int64Ty =
7776 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7777 const Expr *CounterVal = C->getCounterValue();
7778 assert(CounterVal);
7779 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7780 CounterVal->getType(), Int64Ty,
7781 CounterVal->getExprLoc());
7782 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7783 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7784 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7785 getThreadID(CGF, C->getLocStart()),
7786 CntAddr.getPointer()};
7787 llvm::Value *RTLFn;
7788 if (C->getDependencyKind() == OMPC_DEPEND_source)
7789 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7790 else {
7791 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7792 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7793 }
7794 CGF.EmitRuntimeCall(RTLFn, Args);
7795}
7796
Alexey Bataev3c595a62017-08-14 15:01:03 +00007797void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7798 ArrayRef<llvm::Value *> Args,
7799 SourceLocation Loc) const {
7800 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7801
7802 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007803 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007804 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007805 return;
7806 }
7807 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007808 CGF.EmitRuntimeCall(Callee, Args);
7809}
7810
7811void CGOpenMPRuntime::emitOutlinedFunctionCall(
7812 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7813 ArrayRef<llvm::Value *> Args) const {
7814 assert(Loc.isValid() && "Outlined function call location must be valid.");
7815 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007816}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007817
7818Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7819 const VarDecl *NativeParam,
7820 const VarDecl *TargetParam) const {
7821 return CGF.GetAddrOfLocalVar(NativeParam);
7822}