blob: 5ccc77c5cfb3bf0aec3dde331042a8b4d7f7f406 [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"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +000017#include "CGRecordLayout.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000023#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000025#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000029#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000030#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000031#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000032
33using namespace clang;
34using namespace CodeGen;
35
Benjamin Kramerc52193f2014-10-10 13:57:57 +000036namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000037/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000038class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000040 /// \brief Kinds of OpenMP regions used in codegen.
41 enum CGOpenMPRegionKind {
42 /// \brief Region with outlined function for standalone 'parallel'
43 /// directive.
44 ParallelOutlinedRegion,
45 /// \brief Region with outlined function for standalone 'task' directive.
46 TaskOutlinedRegion,
47 /// \brief Region for constructs that do not require function outlining,
48 /// like 'for', 'sections', 'atomic' etc. directives.
49 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000050 /// \brief Region with outlined function for standalone 'target' directive.
51 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 };
Alexey Bataev18095712014-10-10 12:19:54 +000053
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000054 CGOpenMPRegionInfo(const CapturedStmt &CS,
55 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
57 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000060
61 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
63 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000064 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000065 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066
67 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000068 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000070
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000072 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000074 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000075 /// \return LValue for thread id variable. This LValue always has type int32*.
76 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000077
Alexey Bataev48591dd2016-04-20 04:01:36 +000078 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
79
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000080 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000081
Alexey Bataev81c7ea02015-07-03 09:56:58 +000082 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
83
Alexey Bataev25e5b442015-09-15 12:52:43 +000084 bool hasCancel() const { return HasCancel; }
85
Alexey Bataev18095712014-10-10 12:19:54 +000086 static bool classof(const CGCapturedStmtInfo *Info) {
87 return Info->getKind() == CR_OpenMP;
88 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000089
Alexey Bataev48591dd2016-04-20 04:01:36 +000090 ~CGOpenMPRegionInfo() override = default;
91
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000093 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000094 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000095 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000096 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097};
Alexey Bataev18095712014-10-10 12:19:54 +000098
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000100class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000102 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000103 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 OpenMPDirectiveKind Kind, bool HasCancel,
105 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000106 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
107 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000111
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000112 /// \brief Get a variable or parameter for storing global thread id
113 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000114 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000115
Alexey Bataev18095712014-10-10 12:19:54 +0000116 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000117 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000118
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000119 static bool classof(const CGCapturedStmtInfo *Info) {
120 return CGOpenMPRegionInfo::classof(Info) &&
121 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
122 ParallelOutlinedRegion;
123 }
124
Alexey Bataev18095712014-10-10 12:19:54 +0000125private:
126 /// \brief A variable or parameter storing global thread id for OpenMP
127 /// constructs.
128 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000129 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000130};
131
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000134public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000135 class UntiedTaskActionTy final : public PrePostActionTy {
136 bool Untied;
137 const VarDecl *PartIDVar;
138 const RegionCodeGenTy UntiedCodeGen;
139 llvm::SwitchInst *UntiedSwitch = nullptr;
140
141 public:
142 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
143 const RegionCodeGenTy &UntiedCodeGen)
144 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
145 void Enter(CodeGenFunction &CGF) override {
146 if (Untied) {
147 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000148 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000149 CGF.GetAddrOfLocalVar(PartIDVar),
150 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000151 llvm::Value *Res =
152 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
153 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000154 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
155 CGF.EmitBlock(DoneBB);
156 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
157 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
158 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
159 CGF.Builder.GetInsertBlock());
160 emitUntiedSwitch(CGF);
161 }
162 }
163 void emitUntiedSwitch(CodeGenFunction &CGF) const {
164 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000165 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000166 CGF.GetAddrOfLocalVar(PartIDVar),
167 PartIDVar->getType()->castAs<PointerType>());
168 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
169 PartIdLVal);
170 UntiedCodeGen(CGF);
171 CodeGenFunction::JumpDest CurPoint =
172 CGF.getJumpDestInCurrentScope(".untied.next.");
173 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
174 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
175 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
176 CGF.Builder.GetInsertBlock());
177 CGF.EmitBranchThroughCleanup(CurPoint);
178 CGF.EmitBlock(CurPoint.getBlock());
179 }
180 }
181 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
182 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000184 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000185 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 OpenMPDirectiveKind Kind, bool HasCancel,
187 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000188 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000189 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
191 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000192
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193 /// \brief Get a variable or parameter for storing global thread id
194 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
197 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000198 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000199
Alexey Bataev62b63b12015-03-10 07:28:44 +0000200 /// \brief Get the name of the capture helper.
201 StringRef getHelperName() const override { return ".omp_outlined."; }
202
Alexey Bataev48591dd2016-04-20 04:01:36 +0000203 void emitUntiedSwitch(CodeGenFunction &CGF) override {
204 Action.emitUntiedSwitch(CGF);
205 }
206
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000207 static bool classof(const CGCapturedStmtInfo *Info) {
208 return CGOpenMPRegionInfo::classof(Info) &&
209 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
210 TaskOutlinedRegion;
211 }
212
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213private:
214 /// \brief A variable or parameter storing global thread id for OpenMP
215 /// constructs.
216 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000217 /// Action for emitting code for untied tasks.
218 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000219};
220
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000221/// \brief API for inlined captured statement code generation in OpenMP
222/// constructs.
223class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
224public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000226 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000227 OpenMPDirectiveKind Kind, bool HasCancel)
228 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
229 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000231
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000233 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000234 if (OuterRegionInfo)
235 return OuterRegionInfo->getContextValue();
236 llvm_unreachable("No context value for inlined OpenMP region");
237 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000238
Hans Wennborg7eb54642015-09-10 17:07:54 +0000239 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000240 if (OuterRegionInfo) {
241 OuterRegionInfo->setContextValue(V);
242 return;
243 }
244 llvm_unreachable("No context value for inlined OpenMP region");
245 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000246
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000248 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000249 if (OuterRegionInfo)
250 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000251 // If there is no outer outlined region,no need to lookup in a list of
252 // captured variables, we can use the original one.
253 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000255
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000256 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000257 if (OuterRegionInfo)
258 return OuterRegionInfo->getThisFieldDecl();
259 return nullptr;
260 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000261
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 /// \brief Get a variable or parameter for storing global thread id
263 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000264 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000265 if (OuterRegionInfo)
266 return OuterRegionInfo->getThreadIDVariable();
267 return nullptr;
268 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000269
Alexey Bataev311a9282017-10-12 13:51:32 +0000270 /// \brief Get an LValue for the current ThreadID variable.
271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274 llvm_unreachable("No LValue for inlined OpenMP construct");
275 }
276
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000277 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000278 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000279 if (auto *OuterRegionInfo = getOldCSI())
280 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000281 llvm_unreachable("No helper name for inlined OpenMP construct");
282 }
283
Alexey Bataev48591dd2016-04-20 04:01:36 +0000284 void emitUntiedSwitch(CodeGenFunction &CGF) override {
285 if (OuterRegionInfo)
286 OuterRegionInfo->emitUntiedSwitch(CGF);
287 }
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
290
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000291 static bool classof(const CGCapturedStmtInfo *Info) {
292 return CGOpenMPRegionInfo::classof(Info) &&
293 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
294 }
295
Alexey Bataev48591dd2016-04-20 04:01:36 +0000296 ~CGOpenMPInlinedRegionInfo() override = default;
297
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000298private:
299 /// \brief CodeGen info about outer OpenMP region.
300 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000302};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000303
Samuel Antaobed3c462015-10-02 16:14:20 +0000304/// \brief API for captured statement code generation in OpenMP target
305/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000306/// captured fields. The name of the target region has to be unique in a given
307/// application so it is provided by the client, because only the client has
308/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000309class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000310public:
311 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000313 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000314 /*HasCancel=*/false),
315 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000316
317 /// \brief This is unused for target regions because each starts executing
318 /// with a single thread.
319 const VarDecl *getThreadIDVariable() const override { return nullptr; }
320
321 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000322 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000323
324 static bool classof(const CGCapturedStmtInfo *Info) {
325 return CGOpenMPRegionInfo::classof(Info) &&
326 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
327 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000328
329private:
330 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000331};
332
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000333static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000334 llvm_unreachable("No codegen for expressions");
335}
336/// \brief API for generation of expressions captured in a innermost OpenMP
337/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000338class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000339public:
340 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
341 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
342 OMPD_unknown,
343 /*HasCancel=*/false),
344 PrivScope(CGF) {
345 // Make sure the globals captured in the provided statement are local by
346 // using the privatization logic. We assume the same variable is not
347 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000348 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000349 if (!C.capturesVariable() && !C.capturesVariableByCopy())
350 continue;
351
352 const VarDecl *VD = C.getCapturedVar();
353 if (VD->isLocalVarDeclOrParm())
354 continue;
355
356 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
357 /*RefersToEnclosingVariableOrCapture=*/false,
358 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000359 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000360 PrivScope.addPrivate(
361 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000362 }
363 (void)PrivScope.Privatize();
364 }
365
366 /// \brief Lookup the captured field decl for a variable.
367 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000368 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000369 return FD;
370 return nullptr;
371 }
372
373 /// \brief Emit the captured statement body.
374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375 llvm_unreachable("No body for expressions");
376 }
377
378 /// \brief Get a variable or parameter for storing global thread id
379 /// inside OpenMP construct.
380 const VarDecl *getThreadIDVariable() const override {
381 llvm_unreachable("No thread id for expressions");
382 }
383
384 /// \brief Get the name of the capture helper.
385 StringRef getHelperName() const override {
386 llvm_unreachable("No helper name for expressions");
387 }
388
389 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
390
391private:
392 /// Private scope to capture global variables.
393 CodeGenFunction::OMPPrivateScope PrivScope;
394};
395
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000396/// \brief RAII for emitting code of OpenMP constructs.
397class InlinedOpenMPRegionRAII {
398 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000399 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
400 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000401 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000402
403public:
404 /// \brief Constructs region for combined constructs.
405 /// \param CodeGen Code generation sequence for combined directives. Includes
406 /// a list of functions used for code generation of implicitly inlined
407 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000408 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000409 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 : CGF(CGF) {
411 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000412 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
413 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000414 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
415 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
416 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000417 BlockInfo = CGF.BlockInfo;
418 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000419 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000420
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000421 ~InlinedOpenMPRegionRAII() {
422 // Restore original CapturedStmtInfo only if we're done with code emission.
423 auto *OldCSI =
424 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
425 delete CGF.CapturedStmtInfo;
426 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000427 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
428 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000429 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000430 }
431};
432
Alexey Bataev50b3c952016-02-19 10:38:26 +0000433/// \brief Values for bit flags used in the ident_t to describe the fields.
434/// All enumeric elements are named and described in accordance with the code
435/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000436enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000437 /// \brief Use trampoline for internal microtask.
438 OMP_IDENT_IMD = 0x01,
439 /// \brief Use c-style ident structure.
440 OMP_IDENT_KMPC = 0x02,
441 /// \brief Atomic reduction option for kmpc_reduce.
442 OMP_ATOMIC_REDUCE = 0x10,
443 /// \brief Explicit 'barrier' directive.
444 OMP_IDENT_BARRIER_EXPL = 0x20,
445 /// \brief Implicit barrier in code.
446 OMP_IDENT_BARRIER_IMPL = 0x40,
447 /// \brief Implicit barrier in 'for' directive.
448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
449 /// \brief Implicit barrier in 'sections' directive.
450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
451 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000452 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
453 /// Call of __kmp_for_static_init for static loop.
454 OMP_IDENT_WORK_LOOP = 0x200,
455 /// Call of __kmp_for_static_init for sections.
456 OMP_IDENT_WORK_SECTIONS = 0x400,
457 /// Call of __kmp_for_static_init for distribute.
458 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
459 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000460};
461
462/// \brief Describes ident structure that describes a source location.
463/// All descriptions are taken from
464/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
465/// Original structure:
466/// typedef struct ident {
467/// kmp_int32 reserved_1; /**< might be used in Fortran;
468/// see above */
469/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
470/// KMP_IDENT_KMPC identifies this union
471/// member */
472/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
473/// see above */
474///#if USE_ITT_BUILD
475/// /* but currently used for storing
476/// region-specific ITT */
477/// /* contextual information. */
478///#endif /* USE_ITT_BUILD */
479/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
480/// C++ */
481/// char const *psource; /**< String describing the source location.
482/// The string is composed of semi-colon separated
483// fields which describe the source file,
484/// the function and a pair of line numbers that
485/// delimit the construct.
486/// */
487/// } ident_t;
488enum IdentFieldIndex {
489 /// \brief might be used in Fortran
490 IdentField_Reserved_1,
491 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
492 IdentField_Flags,
493 /// \brief Not really used in Fortran any more
494 IdentField_Reserved_2,
495 /// \brief Source[4] in Fortran, do not use for C++
496 IdentField_Reserved_3,
497 /// \brief String describing the source location. The string is composed of
498 /// semi-colon separated fields which describe the source file, the function
499 /// and a pair of line numbers that delimit the construct.
500 IdentField_PSource
501};
502
503/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
504/// the enum sched_type in kmp.h).
505enum OpenMPSchedType {
506 /// \brief Lower bound for default (unordered) versions.
507 OMP_sch_lower = 32,
508 OMP_sch_static_chunked = 33,
509 OMP_sch_static = 34,
510 OMP_sch_dynamic_chunked = 35,
511 OMP_sch_guided_chunked = 36,
512 OMP_sch_runtime = 37,
513 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000514 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000515 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000516 /// \brief Lower bound for 'ordered' versions.
517 OMP_ord_lower = 64,
518 OMP_ord_static_chunked = 65,
519 OMP_ord_static = 66,
520 OMP_ord_dynamic_chunked = 67,
521 OMP_ord_guided_chunked = 68,
522 OMP_ord_runtime = 69,
523 OMP_ord_auto = 70,
524 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000525 /// \brief dist_schedule types
526 OMP_dist_sch_static_chunked = 91,
527 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000528 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
529 /// Set if the monotonic schedule modifier was present.
530 OMP_sch_modifier_monotonic = (1 << 29),
531 /// Set if the nonmonotonic schedule modifier was present.
532 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000533};
534
535enum OpenMPRTLFunction {
536 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
537 /// kmpc_micro microtask, ...);
538 OMPRTL__kmpc_fork_call,
539 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541 OMPRTL__kmpc_threadprivate_cached,
542 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
543 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
544 OMPRTL__kmpc_threadprivate_register,
545 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
546 OMPRTL__kmpc_global_thread_num,
547 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
548 // kmp_critical_name *crit);
549 OMPRTL__kmpc_critical,
550 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
551 // global_tid, kmp_critical_name *crit, uintptr_t hint);
552 OMPRTL__kmpc_critical_with_hint,
553 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
554 // kmp_critical_name *crit);
555 OMPRTL__kmpc_end_critical,
556 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
557 // global_tid);
558 OMPRTL__kmpc_cancel_barrier,
559 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
560 OMPRTL__kmpc_barrier,
561 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
562 OMPRTL__kmpc_for_static_fini,
563 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
564 // global_tid);
565 OMPRTL__kmpc_serialized_parallel,
566 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
567 // global_tid);
568 OMPRTL__kmpc_end_serialized_parallel,
569 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
570 // kmp_int32 num_threads);
571 OMPRTL__kmpc_push_num_threads,
572 // Call to void __kmpc_flush(ident_t *loc);
573 OMPRTL__kmpc_flush,
574 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
575 OMPRTL__kmpc_master,
576 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_end_master,
578 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
579 // int end_part);
580 OMPRTL__kmpc_omp_taskyield,
581 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
582 OMPRTL__kmpc_single,
583 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
584 OMPRTL__kmpc_end_single,
585 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
586 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
587 // kmp_routine_entry_t *task_entry);
588 OMPRTL__kmpc_omp_task_alloc,
589 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
590 // new_task);
591 OMPRTL__kmpc_omp_task,
592 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
593 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
594 // kmp_int32 didit);
595 OMPRTL__kmpc_copyprivate,
596 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
597 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
598 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
599 OMPRTL__kmpc_reduce,
600 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
601 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
602 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
603 // *lck);
604 OMPRTL__kmpc_reduce_nowait,
605 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
606 // kmp_critical_name *lck);
607 OMPRTL__kmpc_end_reduce,
608 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
609 // kmp_critical_name *lck);
610 OMPRTL__kmpc_end_reduce_nowait,
611 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
612 // kmp_task_t * new_task);
613 OMPRTL__kmpc_omp_task_begin_if0,
614 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
615 // kmp_task_t * new_task);
616 OMPRTL__kmpc_omp_task_complete_if0,
617 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
618 OMPRTL__kmpc_ordered,
619 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_end_ordered,
621 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
622 // global_tid);
623 OMPRTL__kmpc_omp_taskwait,
624 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
625 OMPRTL__kmpc_taskgroup,
626 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
627 OMPRTL__kmpc_end_taskgroup,
628 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
629 // int proc_bind);
630 OMPRTL__kmpc_push_proc_bind,
631 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
632 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
633 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
634 OMPRTL__kmpc_omp_task_with_deps,
635 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
636 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
637 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
638 OMPRTL__kmpc_omp_wait_deps,
639 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
640 // global_tid, kmp_int32 cncl_kind);
641 OMPRTL__kmpc_cancellationpoint,
642 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
643 // kmp_int32 cncl_kind);
644 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
646 // kmp_int32 num_teams, kmp_int32 thread_limit);
647 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000648 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
649 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000650 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000651 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
652 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
653 // sched, kmp_uint64 grainsize, void *task_dup);
654 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000655 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
656 // num_dims, struct kmp_dim *dims);
657 OMPRTL__kmpc_doacross_init,
658 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
659 OMPRTL__kmpc_doacross_fini,
660 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
661 // *vec);
662 OMPRTL__kmpc_doacross_post,
663 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
664 // *vec);
665 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000666 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
667 // *data);
668 OMPRTL__kmpc_task_reduction_init,
669 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
670 // *d);
671 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672
673 //
674 // Offloading related calls
675 //
George Rokos63bc9d62017-11-21 18:25:12 +0000676 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
677 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000678 // *arg_types);
679 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000680 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
681 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
682 // *arg_types);
683 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000684 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
685 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
686 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000687 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000688 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
689 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
690 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
691 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
693 OMPRTL__tgt_register_lib,
694 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
695 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000696 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
697 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000698 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000699 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
700 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
701 // *arg_types);
702 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000703 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
704 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000705 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000706 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
707 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
708 // *arg_types);
709 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000710 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
711 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000712 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000713 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
714 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
715 // *arg_types);
716 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000717};
718
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000719/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
720/// region.
721class CleanupTy final : public EHScopeStack::Cleanup {
722 PrePostActionTy *Action;
723
724public:
725 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
726 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
727 if (!CGF.HaveInsertPoint())
728 return;
729 Action->Exit(CGF);
730 }
731};
732
Hans Wennborg7eb54642015-09-10 17:07:54 +0000733} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000734
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000735void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
736 CodeGenFunction::RunCleanupsScope Scope(CGF);
737 if (PrePostAction) {
738 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
739 Callback(CodeGen, CGF, *PrePostAction);
740 } else {
741 PrePostActionTy Action;
742 Callback(CodeGen, CGF, Action);
743 }
744}
745
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000746/// Check if the combiner is a call to UDR combiner and if it is so return the
747/// UDR decl used for reduction.
748static const OMPDeclareReductionDecl *
749getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000750 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
751 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
752 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000753 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000754 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000755 return DRD;
756 return nullptr;
757}
758
759static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
760 const OMPDeclareReductionDecl *DRD,
761 const Expr *InitOp,
762 Address Private, Address Original,
763 QualType Ty) {
764 if (DRD->getInitializer()) {
765 std::pair<llvm::Function *, llvm::Function *> Reduction =
766 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000767 const auto *CE = cast<CallExpr>(InitOp);
768 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000769 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
770 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000771 const auto *LHSDRE =
772 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
773 const auto *RHSDRE =
774 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000775 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
776 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000777 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000778 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000779 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000780 (void)PrivateScope.Privatize();
781 RValue Func = RValue::get(Reduction.second);
782 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
783 CGF.EmitIgnoredExpr(InitOp);
784 } else {
785 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000786 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000787 auto *GV = new llvm::GlobalVariable(
788 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000789 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000790 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
791 RValue InitRVal;
792 switch (CGF.getEvaluationKind(Ty)) {
793 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Complex:
797 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000798 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000799 break;
800 case TEK_Aggregate:
801 InitRVal = RValue::getAggregate(LV.getAddress());
802 break;
803 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000804 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000805 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
806 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
807 /*IsInitializer=*/false);
808 }
809}
810
811/// \brief Emit initialization of arrays of complex types.
812/// \param DestAddr Address of the array.
813/// \param Type Type of array.
814/// \param Init Initial expression of array.
815/// \param SrcAddr Address of the original array.
816static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000817 QualType Type, bool EmitDeclareReductionInit,
818 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000819 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000820 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000821 // Perform element-by-element initialization.
822 QualType ElementTy;
823
824 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000825 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
826 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000827 DestAddr =
828 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
829 if (DRD)
830 SrcAddr =
831 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
832
833 llvm::Value *SrcBegin = nullptr;
834 if (DRD)
835 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000836 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000837 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000838 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000839 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000840 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
841 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
842 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000843 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
844 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
845
846 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000847 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000848 CGF.EmitBlock(BodyBB);
849
850 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
851
852 llvm::PHINode *SrcElementPHI = nullptr;
853 Address SrcElementCurrent = Address::invalid();
854 if (DRD) {
855 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
856 "omp.arraycpy.srcElementPast");
857 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
858 SrcElementCurrent =
859 Address(SrcElementPHI,
860 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
861 }
862 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
863 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
864 DestElementPHI->addIncoming(DestBegin, EntryBB);
865 Address DestElementCurrent =
866 Address(DestElementPHI,
867 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
868
869 // Emit copy.
870 {
871 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000872 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000873 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
874 SrcElementCurrent, ElementTy);
875 } else
876 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
877 /*IsInitializer=*/false);
878 }
879
880 if (DRD) {
881 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000882 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000883 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
884 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
885 }
886
887 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000888 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
890 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000891 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000892 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
893 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
894 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
895
896 // Done.
897 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
898}
899
Alexey Bataev92327c52018-03-26 16:40:55 +0000900static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
901isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000902 for (const Decl *D : VD->redecls()) {
Alexey Bataev92327c52018-03-26 16:40:55 +0000903 if (!D->hasAttrs())
904 continue;
905 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
906 return Attr->getMapType();
907 }
Alexey Bataevfb388282018-05-01 14:09:46 +0000908 if (const auto *V = dyn_cast<VarDecl>(VD)) {
909 if (const VarDecl *TD = V->getTemplateInstantiationPattern())
910 return isDeclareTargetDeclaration(TD);
911 } else if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
912 if (const auto *TD = FD->getTemplateInstantiationPattern())
913 return isDeclareTargetDeclaration(TD);
914 }
915
Alexey Bataev92327c52018-03-26 16:40:55 +0000916 return llvm::None;
917}
918
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000920 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921}
922
923LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
924 const Expr *E) {
925 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
926 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
927 return LValue();
928}
929
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930void ReductionCodeGen::emitAggregateInitialization(
931 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
932 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933 // Emit VarDecl with copy init for arrays.
934 // Get the address of the original variable captured in current
935 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000936 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000937 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000938 bool EmitDeclareReductionInit =
939 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000941 EmitDeclareReductionInit,
942 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
943 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000944 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000945}
946
947ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
948 ArrayRef<const Expr *> Privates,
949 ArrayRef<const Expr *> ReductionOps) {
950 ClausesData.reserve(Shareds.size());
951 SharedAddresses.reserve(Shareds.size());
952 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000953 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 auto IPriv = Privates.begin();
955 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000956 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957 ClausesData.emplace_back(Ref, *IPriv, *IRed);
958 std::advance(IPriv, 1);
959 std::advance(IRed, 1);
960 }
961}
962
963void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
964 assert(SharedAddresses.size() == N &&
965 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000966 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
967 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
968 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969}
970
971void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000972 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000973 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
974 QualType PrivateType = PrivateVD->getType();
975 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000976 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 Sizes.emplace_back(
978 CGF.getTypeSize(
979 SharedAddresses[N].first.getType().getNonReferenceType()),
980 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 return;
982 }
983 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000984 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000985 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000986 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
987 ->getElementType();
988 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000989 if (AsArraySection) {
990 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
991 SharedAddresses[N].first.getPointer());
992 Size = CGF.Builder.CreateNUWAdd(
993 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000994 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000995 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000996 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000997 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001000 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001001 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1002 CGF,
1003 cast<OpaqueValueExpr>(
1004 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005 RValue::get(Size));
1006 CGF.EmitVariablyModifiedType(PrivateType);
1007}
1008
1009void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
1010 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001011 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001012 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001014 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001015 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001016 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 "items.");
1018 return;
1019 }
1020 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1021 CGF,
1022 cast<OpaqueValueExpr>(
1023 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1024 RValue::get(Size));
1025 CGF.EmitVariablyModifiedType(PrivateType);
1026}
1027
1028void ReductionCodeGen::emitInitialization(
1029 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1030 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1031 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001032 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001033 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001034 const OMPDeclareReductionDecl *DRD =
1035 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001036 QualType PrivateType = PrivateVD->getType();
1037 PrivateAddr = CGF.Builder.CreateElementBitCast(
1038 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1039 QualType SharedType = SharedAddresses[N].first.getType();
1040 SharedLVal = CGF.MakeAddrLValue(
1041 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1042 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001043 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001044 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001045 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001046 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001047 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1048 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1049 PrivateAddr, SharedLVal.getAddress(),
1050 SharedLVal.getType());
1051 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1052 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1053 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1054 PrivateVD->getType().getQualifiers(),
1055 /*IsInitializer=*/false);
1056 }
1057}
1058
1059bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001060 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001061 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1062 QualType PrivateType = PrivateVD->getType();
1063 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1064 return DTorKind != QualType::DK_none;
1065}
1066
1067void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1068 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001069 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001070 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1071 QualType PrivateType = PrivateVD->getType();
1072 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1073 if (needCleanups(N)) {
1074 PrivateAddr = CGF.Builder.CreateElementBitCast(
1075 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1076 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1077 }
1078}
1079
1080static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1081 LValue BaseLV) {
1082 BaseTy = BaseTy.getNonReferenceType();
1083 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1084 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001085 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001086 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001087 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001088 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1089 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001090 }
1091 BaseTy = BaseTy->getPointeeType();
1092 }
1093 return CGF.MakeAddrLValue(
1094 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1095 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001096 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001097 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001098}
1099
1100static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1101 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1102 llvm::Value *Addr) {
1103 Address Tmp = Address::invalid();
1104 Address TopTmp = Address::invalid();
1105 Address MostTopTmp = Address::invalid();
1106 BaseTy = BaseTy.getNonReferenceType();
1107 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1108 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1109 Tmp = CGF.CreateMemTemp(BaseTy);
1110 if (TopTmp.isValid())
1111 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1112 else
1113 MostTopTmp = Tmp;
1114 TopTmp = Tmp;
1115 BaseTy = BaseTy->getPointeeType();
1116 }
1117 llvm::Type *Ty = BaseLVType;
1118 if (Tmp.isValid())
1119 Ty = Tmp.getElementType();
1120 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1121 if (Tmp.isValid()) {
1122 CGF.Builder.CreateStore(Addr, Tmp);
1123 return MostTopTmp;
1124 }
1125 return Address(Addr, BaseLVAlignment);
1126}
1127
Alexey Bataev1c44e152018-03-06 18:59:43 +00001128static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001129 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001130 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1131 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1132 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001133 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001134 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 Base = TempASE->getBase()->IgnoreParenImpCasts();
1136 DE = cast<DeclRefExpr>(Base);
1137 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001138 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1139 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1140 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001141 Base = TempASE->getBase()->IgnoreParenImpCasts();
1142 DE = cast<DeclRefExpr>(Base);
1143 OrigVD = cast<VarDecl>(DE->getDecl());
1144 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001145 return OrigVD;
1146}
1147
1148Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1149 Address PrivateAddr) {
1150 const DeclRefExpr *DE;
1151 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001152 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001153 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001154 LValue BaseLValue =
1155 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1156 OriginalBaseLValue);
1157 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1158 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001159 llvm::Value *PrivatePointer =
1160 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1161 PrivateAddr.getPointer(),
1162 SharedAddresses[N].first.getAddress().getType());
1163 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001164 return castToBase(CGF, OrigVD->getType(),
1165 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001166 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001167 OriginalBaseLValue.getAlignment(), Ptr);
1168 }
1169 BaseDecls.emplace_back(
1170 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1171 return PrivateAddr;
1172}
1173
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001174bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001175 const OMPDeclareReductionDecl *DRD =
1176 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001177 return DRD && DRD->getInitializer();
1178}
1179
Alexey Bataev18095712014-10-10 12:19:54 +00001180LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001181 return CGF.EmitLoadOfPointerLValue(
1182 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001184}
1185
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001186void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001187 if (!CGF.HaveInsertPoint())
1188 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189 // 1.2.2 OpenMP Language Terminology
1190 // Structured block - An executable statement with a single entry at the
1191 // top and a single exit at the bottom.
1192 // The point of exit cannot be a branch out of the structured block.
1193 // longjmp() and throw() must not violate the entry/exit criteria.
1194 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001195 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001197}
1198
Alexey Bataev62b63b12015-03-10 07:28:44 +00001199LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1200 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001201 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1202 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001203 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001204}
1205
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001206static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1207 QualType FieldTy) {
1208 auto *Field = FieldDecl::Create(
1209 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1210 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1211 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1212 Field->setAccess(AS_public);
1213 DC->addDecl(Field);
1214 return Field;
1215}
1216
Alexey Bataev18fa2322018-05-02 14:20:50 +00001217CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1218 StringRef Separator)
1219 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1220 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001221 ASTContext &C = CGM.getContext();
1222 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1223 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1224 RD->startDefinition();
1225 // reserved_1
1226 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1227 // flags
1228 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1229 // reserved_2
1230 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1231 // reserved_3
1232 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1233 // psource
1234 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1235 RD->completeDefinition();
1236 IdentQTy = C.getRecordType(RD);
1237 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001238 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001239
1240 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001241}
1242
Alexey Bataev91797552015-03-18 04:13:55 +00001243void CGOpenMPRuntime::clear() {
1244 InternalVars.clear();
1245}
1246
Alexey Bataev18fa2322018-05-02 14:20:50 +00001247std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1248 SmallString<128> Buffer;
1249 llvm::raw_svector_ostream OS(Buffer);
1250 StringRef Sep = FirstSeparator;
1251 for (StringRef Part : Parts) {
1252 OS << Sep << Part;
1253 Sep = Separator;
1254 }
1255 return OS.str();
1256}
1257
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001258static llvm::Function *
1259emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1260 const Expr *CombinerInitializer, const VarDecl *In,
1261 const VarDecl *Out, bool IsCombiner) {
1262 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001263 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001264 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1265 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001266 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001267 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001268 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001269 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001270 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001271 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001272 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001273 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001274 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001275 std::string Name = CGM.getOpenMPRuntime().getName(
1276 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1277 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1278 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001279 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001280 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001281 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001282 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001283 CodeGenFunction CGF(CGM);
1284 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1285 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001286 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1287 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001288 CodeGenFunction::OMPPrivateScope Scope(CGF);
1289 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001290 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001291 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1292 .getAddress();
1293 });
1294 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001295 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001296 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1297 .getAddress();
1298 });
1299 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001300 if (!IsCombiner && Out->hasInit() &&
1301 !CGF.isTrivialInitializer(Out->getInit())) {
1302 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1303 Out->getType().getQualifiers(),
1304 /*IsInitializer=*/true);
1305 }
1306 if (CombinerInitializer)
1307 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001308 Scope.ForceCleanup();
1309 CGF.FinishFunction();
1310 return Fn;
1311}
1312
1313void CGOpenMPRuntime::emitUserDefinedReduction(
1314 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1315 if (UDRMap.count(D) > 0)
1316 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001317 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 if (!In || !Out) {
1319 In = &C.Idents.get("omp_in");
1320 Out = &C.Idents.get("omp_out");
1321 }
1322 llvm::Function *Combiner = emitCombinerOrInitializer(
1323 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1324 cast<VarDecl>(D->lookup(Out).front()),
1325 /*IsCombiner=*/true);
1326 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001327 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001328 if (!Priv || !Orig) {
1329 Priv = &C.Idents.get("omp_priv");
1330 Orig = &C.Idents.get("omp_orig");
1331 }
1332 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001333 CGM, D->getType(),
1334 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1335 : nullptr,
1336 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001337 cast<VarDecl>(D->lookup(Priv).front()),
1338 /*IsCombiner=*/false);
1339 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001340 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001341 if (CGF) {
1342 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1343 Decls.second.push_back(D);
1344 }
1345}
1346
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001347std::pair<llvm::Function *, llvm::Function *>
1348CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1349 auto I = UDRMap.find(D);
1350 if (I != UDRMap.end())
1351 return I->second;
1352 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1353 return UDRMap.lookup(D);
1354}
1355
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001356static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1357 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1358 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1359 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001360 assert(ThreadIDVar->getType()->isPointerType() &&
1361 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001362 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001363 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001364 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001365 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001366 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001367 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001368 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001369 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001370 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001371 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001372 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001373 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001374 else if (const auto *OPFD =
1375 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001376 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001377 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001378 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1379 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001380 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001381 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001382 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001383 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001384}
1385
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001386llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1387 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1388 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1389 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1390 return emitParallelOrTeamsOutlinedFunction(
1391 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1392}
1393
1394llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1395 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1396 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1397 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1398 return emitParallelOrTeamsOutlinedFunction(
1399 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1400}
1401
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001402llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1403 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001404 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1405 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1406 bool Tied, unsigned &NumberOfParts) {
1407 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1408 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001409 llvm::Value *ThreadID = getThreadID(CGF, D.getLocStart());
1410 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001411 llvm::Value *TaskArgs[] = {
1412 UpLoc, ThreadID,
1413 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1414 TaskTVar->getType()->castAs<PointerType>())
1415 .getPointer()};
1416 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1417 };
1418 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1419 UntiedCodeGen);
1420 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001421 assert(!ThreadIDVar->getType()->isPointerType() &&
1422 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001423 const OpenMPDirectiveKind Region =
1424 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1425 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001426 const CapturedStmt *CS = D.getCapturedStmt(Region);
1427 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001428 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001429 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1430 InnermostKind,
1431 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001432 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001433 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001434 if (!Tied)
1435 NumberOfParts = Action.getNumberOfParts();
1436 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001437}
1438
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001439static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1440 const RecordDecl *RD, const CGRecordLayout &RL,
1441 ArrayRef<llvm::Constant *> Data) {
1442 llvm::StructType *StructTy = RL.getLLVMType();
1443 unsigned PrevIdx = 0;
1444 ConstantInitBuilder CIBuilder(CGM);
1445 auto DI = Data.begin();
1446 for (const FieldDecl *FD : RD->fields()) {
1447 unsigned Idx = RL.getLLVMFieldNo(FD);
1448 // Fill the alignment.
1449 for (unsigned I = PrevIdx; I < Idx; ++I)
1450 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1451 PrevIdx = Idx + 1;
1452 Fields.add(*DI);
1453 ++DI;
1454 }
1455}
1456
1457template <class... As>
1458static llvm::GlobalVariable *
1459createConstantGlobalStruct(CodeGenModule &CGM, QualType Ty,
1460 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1461 As &&... Args) {
1462 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1463 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1464 ConstantInitBuilder CIBuilder(CGM);
1465 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1466 buildStructValue(Fields, CGM, RD, RL, Data);
1467 return Fields.finishAndCreateGlobal(
1468 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1469 /*isConstant=*/true, std::forward<As>(Args)...);
1470}
1471
1472template <typename T>
1473void createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1474 ArrayRef<llvm::Constant *> Data,
1475 T &Parent) {
1476 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1477 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1478 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1479 buildStructValue(Fields, CGM, RD, RL, Data);
1480 Fields.finishAndAddTo(Parent);
1481}
1482
Alexey Bataev50b3c952016-02-19 10:38:26 +00001483Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001484 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001485 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 if (!Entry) {
1487 if (!DefaultOpenMPPSource) {
1488 // Initialize default location for psource field of ident_t structure of
1489 // all ident_t objects. Format is ";file;function;line;column;;".
1490 // Taken from
1491 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1492 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001493 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001494 DefaultOpenMPPSource =
1495 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1496 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001497
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001498 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1499 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1500 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1501 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1502 DefaultOpenMPPSource};
1503 llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1504 CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1505 DefaultOpenMPLocation->setUnnamedAddr(
1506 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001507
John McCall7f416cc2015-09-08 08:05:57 +00001508 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001509 }
John McCall7f416cc2015-09-08 08:05:57 +00001510 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001511}
1512
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001513llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1514 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001515 unsigned Flags) {
1516 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001517 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001518 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001519 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001520 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001521
1522 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1523
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001524 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001525 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001526 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1527 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001528 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001529
Alexander Musmanc6388682014-12-15 07:07:06 +00001530 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1531 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001532 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001533 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001534 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001535 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001536 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001537 LocValue = AI;
1538
1539 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1540 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001541 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001542 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001543 }
1544
1545 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001546 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1547 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1548 LValue PSource =
1549 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001550
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001551 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001552 if (OMPDebugLoc == nullptr) {
1553 SmallString<128> Buffer2;
1554 llvm::raw_svector_ostream OS2(Buffer2);
1555 // Build debug location
1556 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1557 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001558 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001559 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001560 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1561 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1562 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001563 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001564 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001565 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001566
John McCall7f416cc2015-09-08 08:05:57 +00001567 // Our callers always pass this to a runtime function, so for
1568 // convenience, go ahead and return a naked pointer.
1569 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001570}
1571
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001572llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1573 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001574 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1575
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001576 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001577 // Check whether we've already cached a load of the thread id in this
1578 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001579 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001580 if (I != OpenMPLocThreadIDMap.end()) {
1581 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001582 if (ThreadID != nullptr)
1583 return ThreadID;
1584 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001585 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001586 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1587 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001588 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001589 if (auto *OMPRegionInfo =
1590 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1591 if (OMPRegionInfo->getThreadIDVariable()) {
1592 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001593 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001594 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001595 // If value loaded in entry block, cache it and use it everywhere in
1596 // function.
1597 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1598 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1599 Elem.second.ThreadID = ThreadID;
1600 }
1601 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001602 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001603 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001604 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001605
1606 // This is not an outlined function region - need to call __kmpc_int32
1607 // kmpc_global_thread_num(ident_t *loc).
1608 // Generate thread id value and cache this value for use across the
1609 // function.
1610 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1611 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001612 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001613 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1614 emitUpdateLocation(CGF, Loc));
1615 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001616 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001617 Elem.second.ThreadID = Call;
1618 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001619}
1620
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001621void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001622 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001623 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1624 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001625 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001626 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001627 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001628 FunctionUDRMap.erase(CGF.CurFn);
1629 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001630}
1631
1632llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001633 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001634}
1635
1636llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001637 if (!Kmpc_MicroTy) {
1638 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1639 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1640 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1641 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1642 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001643 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1644}
1645
1646llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001647CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001648 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001649 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001650 case OMPRTL__kmpc_fork_call: {
1651 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1652 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001653 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1654 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001655 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001657 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1658 break;
1659 }
1660 case OMPRTL__kmpc_global_thread_num: {
1661 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001662 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001663 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001664 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001665 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1666 break;
1667 }
Alexey Bataev97720002014-11-11 04:05:39 +00001668 case OMPRTL__kmpc_threadprivate_cached: {
1669 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1670 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1671 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1672 CGM.VoidPtrTy, CGM.SizeTy,
1673 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001674 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001675 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1677 break;
1678 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001679 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001680 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1681 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001682 llvm::Type *TypeParams[] = {
1683 getIdentTyPointerTy(), CGM.Int32Ty,
1684 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001685 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1688 break;
1689 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001690 case OMPRTL__kmpc_critical_with_hint: {
1691 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1692 // kmp_critical_name *crit, uintptr_t hint);
1693 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1694 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1695 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001696 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1698 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1699 break;
1700 }
Alexey Bataev97720002014-11-11 04:05:39 +00001701 case OMPRTL__kmpc_threadprivate_register: {
1702 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1703 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1704 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001705 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001706 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1707 /*isVarArg*/ false)->getPointerTo();
1708 // typedef void *(*kmpc_cctor)(void *, void *);
1709 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001710 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001711 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001712 /*isVarArg*/ false)
1713 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001714 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001715 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001716 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1717 ->getPointerTo();
1718 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1719 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001720 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001721 /*isVarArg*/ false);
1722 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1723 break;
1724 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001725 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001726 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1727 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001728 llvm::Type *TypeParams[] = {
1729 getIdentTyPointerTy(), CGM.Int32Ty,
1730 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1734 break;
1735 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001736 case OMPRTL__kmpc_cancel_barrier: {
1737 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1738 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001740 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001741 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001743 break;
1744 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001745 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001746 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001747 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001748 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001749 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1750 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1751 break;
1752 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001753 case OMPRTL__kmpc_for_static_fini: {
1754 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1755 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001756 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001757 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1758 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1759 break;
1760 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001761 case OMPRTL__kmpc_push_num_threads: {
1762 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1763 // kmp_int32 num_threads)
1764 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1765 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001766 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001767 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1768 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1769 break;
1770 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001771 case OMPRTL__kmpc_serialized_parallel: {
1772 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1773 // global_tid);
1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001776 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1778 break;
1779 }
1780 case OMPRTL__kmpc_end_serialized_parallel: {
1781 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1782 // global_tid);
1783 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001784 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001785 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1787 break;
1788 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001789 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001790 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001791 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001792 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1795 break;
1796 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001797 case OMPRTL__kmpc_master: {
1798 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001800 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001801 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1803 break;
1804 }
1805 case OMPRTL__kmpc_end_master: {
1806 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1807 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001808 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001809 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1810 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1811 break;
1812 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001813 case OMPRTL__kmpc_omp_taskyield: {
1814 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1815 // int end_part);
1816 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001817 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001818 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1819 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1820 break;
1821 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001822 case OMPRTL__kmpc_single: {
1823 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1824 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001825 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001826 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1827 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1828 break;
1829 }
1830 case OMPRTL__kmpc_end_single: {
1831 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1832 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001833 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001834 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1835 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1836 break;
1837 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001838 case OMPRTL__kmpc_omp_task_alloc: {
1839 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1840 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1841 // kmp_routine_entry_t *task_entry);
1842 assert(KmpRoutineEntryPtrTy != nullptr &&
1843 "Type kmp_routine_entry_t must be created.");
1844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1845 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1846 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001847 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001848 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1850 break;
1851 }
1852 case OMPRTL__kmpc_omp_task: {
1853 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1854 // *new_task);
1855 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1856 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001857 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001858 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1859 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1860 break;
1861 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001862 case OMPRTL__kmpc_copyprivate: {
1863 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001864 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001865 // kmp_int32 didit);
1866 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1867 auto *CpyFnTy =
1868 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001869 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001870 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1871 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001872 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001873 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1874 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1875 break;
1876 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001877 case OMPRTL__kmpc_reduce: {
1878 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1879 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1880 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1881 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1882 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1883 /*isVarArg=*/false);
1884 llvm::Type *TypeParams[] = {
1885 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1886 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1887 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001888 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001889 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1890 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1891 break;
1892 }
1893 case OMPRTL__kmpc_reduce_nowait: {
1894 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1895 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1896 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1897 // *lck);
1898 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1899 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1900 /*isVarArg=*/false);
1901 llvm::Type *TypeParams[] = {
1902 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1903 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1904 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001905 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001906 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1907 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1908 break;
1909 }
1910 case OMPRTL__kmpc_end_reduce: {
1911 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1912 // kmp_critical_name *lck);
1913 llvm::Type *TypeParams[] = {
1914 getIdentTyPointerTy(), CGM.Int32Ty,
1915 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001916 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001917 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1918 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1919 break;
1920 }
1921 case OMPRTL__kmpc_end_reduce_nowait: {
1922 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1923 // kmp_critical_name *lck);
1924 llvm::Type *TypeParams[] = {
1925 getIdentTyPointerTy(), CGM.Int32Ty,
1926 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001927 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001928 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1929 RTLFn =
1930 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1931 break;
1932 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001933 case OMPRTL__kmpc_omp_task_begin_if0: {
1934 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1935 // *new_task);
1936 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1937 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001938 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001939 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1940 RTLFn =
1941 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1942 break;
1943 }
1944 case OMPRTL__kmpc_omp_task_complete_if0: {
1945 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1946 // *new_task);
1947 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1948 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001949 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1952 /*Name=*/"__kmpc_omp_task_complete_if0");
1953 break;
1954 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001955 case OMPRTL__kmpc_ordered: {
1956 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001958 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001959 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1960 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1961 break;
1962 }
1963 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001964 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001965 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001966 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001967 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1968 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1969 break;
1970 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001971 case OMPRTL__kmpc_omp_taskwait: {
1972 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001974 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001975 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1976 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1977 break;
1978 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001979 case OMPRTL__kmpc_taskgroup: {
1980 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1981 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001982 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001983 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1984 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1985 break;
1986 }
1987 case OMPRTL__kmpc_end_taskgroup: {
1988 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1989 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001990 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001991 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1992 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1993 break;
1994 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001995 case OMPRTL__kmpc_push_proc_bind: {
1996 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1997 // int proc_bind)
1998 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001999 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002000 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2001 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2002 break;
2003 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002004 case OMPRTL__kmpc_omp_task_with_deps: {
2005 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2006 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2007 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2008 llvm::Type *TypeParams[] = {
2009 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2010 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002011 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002012 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2013 RTLFn =
2014 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2015 break;
2016 }
2017 case OMPRTL__kmpc_omp_wait_deps: {
2018 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2019 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2020 // kmp_depend_info_t *noalias_dep_list);
2021 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2022 CGM.Int32Ty, CGM.VoidPtrTy,
2023 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002024 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002025 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2026 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2027 break;
2028 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002029 case OMPRTL__kmpc_cancellationpoint: {
2030 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2031 // global_tid, kmp_int32 cncl_kind)
2032 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002033 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002034 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2035 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2036 break;
2037 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002038 case OMPRTL__kmpc_cancel: {
2039 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2040 // kmp_int32 cncl_kind)
2041 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002042 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002043 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2044 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2045 break;
2046 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002047 case OMPRTL__kmpc_push_num_teams: {
2048 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2049 // kmp_int32 num_teams, kmp_int32 num_threads)
2050 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2051 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002052 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002053 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2054 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2055 break;
2056 }
2057 case OMPRTL__kmpc_fork_teams: {
2058 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2059 // microtask, ...);
2060 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2061 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002062 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002063 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2064 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2065 break;
2066 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002067 case OMPRTL__kmpc_taskloop: {
2068 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2069 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2070 // sched, kmp_uint64 grainsize, void *task_dup);
2071 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2072 CGM.IntTy,
2073 CGM.VoidPtrTy,
2074 CGM.IntTy,
2075 CGM.Int64Ty->getPointerTo(),
2076 CGM.Int64Ty->getPointerTo(),
2077 CGM.Int64Ty,
2078 CGM.IntTy,
2079 CGM.IntTy,
2080 CGM.Int64Ty,
2081 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002082 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002083 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2084 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2085 break;
2086 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002087 case OMPRTL__kmpc_doacross_init: {
2088 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2089 // num_dims, struct kmp_dim *dims);
2090 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2091 CGM.Int32Ty,
2092 CGM.Int32Ty,
2093 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002094 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002095 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2096 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2097 break;
2098 }
2099 case OMPRTL__kmpc_doacross_fini: {
2100 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2101 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002102 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002103 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2104 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2105 break;
2106 }
2107 case OMPRTL__kmpc_doacross_post: {
2108 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2109 // *vec);
2110 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2111 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002112 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002113 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2114 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2115 break;
2116 }
2117 case OMPRTL__kmpc_doacross_wait: {
2118 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2119 // *vec);
2120 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2121 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002122 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002123 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2124 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2125 break;
2126 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002127 case OMPRTL__kmpc_task_reduction_init: {
2128 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2129 // *data);
2130 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002131 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002132 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2133 RTLFn =
2134 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2135 break;
2136 }
2137 case OMPRTL__kmpc_task_reduction_get_th_data: {
2138 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2139 // *d);
2140 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002141 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002142 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2143 RTLFn = CGM.CreateRuntimeFunction(
2144 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2145 break;
2146 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002147 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002148 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2149 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002150 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002151 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002152 CGM.VoidPtrTy,
2153 CGM.Int32Ty,
2154 CGM.VoidPtrPtrTy,
2155 CGM.VoidPtrPtrTy,
2156 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002157 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002158 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002159 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2160 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2161 break;
2162 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002163 case OMPRTL__tgt_target_nowait: {
2164 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2165 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2166 // int64_t *arg_types);
2167 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2168 CGM.VoidPtrTy,
2169 CGM.Int32Ty,
2170 CGM.VoidPtrPtrTy,
2171 CGM.VoidPtrPtrTy,
2172 CGM.SizeTy->getPointerTo(),
2173 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002174 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002175 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2176 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2177 break;
2178 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002179 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002180 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002181 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002182 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2183 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002184 CGM.VoidPtrTy,
2185 CGM.Int32Ty,
2186 CGM.VoidPtrPtrTy,
2187 CGM.VoidPtrPtrTy,
2188 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002189 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002190 CGM.Int32Ty,
2191 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002192 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002193 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2194 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2195 break;
2196 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002197 case OMPRTL__tgt_target_teams_nowait: {
2198 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2199 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2200 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2201 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2202 CGM.VoidPtrTy,
2203 CGM.Int32Ty,
2204 CGM.VoidPtrPtrTy,
2205 CGM.VoidPtrPtrTy,
2206 CGM.SizeTy->getPointerTo(),
2207 CGM.Int64Ty->getPointerTo(),
2208 CGM.Int32Ty,
2209 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002210 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002211 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2212 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2213 break;
2214 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002215 case OMPRTL__tgt_register_lib: {
2216 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2217 QualType ParamTy =
2218 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2219 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002220 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002221 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2222 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2223 break;
2224 }
2225 case OMPRTL__tgt_unregister_lib: {
2226 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2227 QualType ParamTy =
2228 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2229 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002230 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2232 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2233 break;
2234 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002235 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002236 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2237 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2238 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002239 CGM.Int32Ty,
2240 CGM.VoidPtrPtrTy,
2241 CGM.VoidPtrPtrTy,
2242 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002243 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002244 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002245 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2246 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2247 break;
2248 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002249 case OMPRTL__tgt_target_data_begin_nowait: {
2250 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2251 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2252 // *arg_types);
2253 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2254 CGM.Int32Ty,
2255 CGM.VoidPtrPtrTy,
2256 CGM.VoidPtrPtrTy,
2257 CGM.SizeTy->getPointerTo(),
2258 CGM.Int64Ty->getPointerTo()};
2259 auto *FnTy =
2260 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2261 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2262 break;
2263 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002264 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002265 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2266 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2267 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002268 CGM.Int32Ty,
2269 CGM.VoidPtrPtrTy,
2270 CGM.VoidPtrPtrTy,
2271 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002272 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002273 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002274 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2275 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2276 break;
2277 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002278 case OMPRTL__tgt_target_data_end_nowait: {
2279 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2280 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2281 // *arg_types);
2282 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2283 CGM.Int32Ty,
2284 CGM.VoidPtrPtrTy,
2285 CGM.VoidPtrPtrTy,
2286 CGM.SizeTy->getPointerTo(),
2287 CGM.Int64Ty->getPointerTo()};
2288 auto *FnTy =
2289 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2290 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2291 break;
2292 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002293 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002294 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2295 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2296 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002297 CGM.Int32Ty,
2298 CGM.VoidPtrPtrTy,
2299 CGM.VoidPtrPtrTy,
2300 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002301 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002302 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002303 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2304 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2305 break;
2306 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002307 case OMPRTL__tgt_target_data_update_nowait: {
2308 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2309 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2310 // *arg_types);
2311 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2312 CGM.Int32Ty,
2313 CGM.VoidPtrPtrTy,
2314 CGM.VoidPtrPtrTy,
2315 CGM.SizeTy->getPointerTo(),
2316 CGM.Int64Ty->getPointerTo()};
2317 auto *FnTy =
2318 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2319 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2320 break;
2321 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002322 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002323 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002324 return RTLFn;
2325}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002326
Alexander Musman21212e42015-03-13 10:38:23 +00002327llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2328 bool IVSigned) {
2329 assert((IVSize == 32 || IVSize == 64) &&
2330 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002331 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2332 : "__kmpc_for_static_init_4u")
2333 : (IVSigned ? "__kmpc_for_static_init_8"
2334 : "__kmpc_for_static_init_8u");
2335 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2336 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002337 llvm::Type *TypeParams[] = {
2338 getIdentTyPointerTy(), // loc
2339 CGM.Int32Ty, // tid
2340 CGM.Int32Ty, // schedtype
2341 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2342 PtrTy, // p_lower
2343 PtrTy, // p_upper
2344 PtrTy, // p_stride
2345 ITy, // incr
2346 ITy // chunk
2347 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002348 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002349 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2350 return CGM.CreateRuntimeFunction(FnTy, Name);
2351}
2352
Alexander Musman92bdaab2015-03-12 13:37:50 +00002353llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2354 bool IVSigned) {
2355 assert((IVSize == 32 || IVSize == 64) &&
2356 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002357 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002358 IVSize == 32
2359 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2360 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002361 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002362 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2363 CGM.Int32Ty, // tid
2364 CGM.Int32Ty, // schedtype
2365 ITy, // lower
2366 ITy, // upper
2367 ITy, // stride
2368 ITy // chunk
2369 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002370 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002371 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2372 return CGM.CreateRuntimeFunction(FnTy, Name);
2373}
2374
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002375llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2376 bool IVSigned) {
2377 assert((IVSize == 32 || IVSize == 64) &&
2378 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002379 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002380 IVSize == 32
2381 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2382 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2383 llvm::Type *TypeParams[] = {
2384 getIdentTyPointerTy(), // loc
2385 CGM.Int32Ty, // tid
2386 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002387 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002388 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2389 return CGM.CreateRuntimeFunction(FnTy, Name);
2390}
2391
Alexander Musman92bdaab2015-03-12 13:37:50 +00002392llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2393 bool IVSigned) {
2394 assert((IVSize == 32 || IVSize == 64) &&
2395 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002396 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002397 IVSize == 32
2398 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2399 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002400 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2401 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002402 llvm::Type *TypeParams[] = {
2403 getIdentTyPointerTy(), // loc
2404 CGM.Int32Ty, // tid
2405 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2406 PtrTy, // p_lower
2407 PtrTy, // p_upper
2408 PtrTy // p_stride
2409 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002410 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002411 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2412 return CGM.CreateRuntimeFunction(FnTy, Name);
2413}
2414
Alexey Bataev03f270c2018-03-30 18:31:07 +00002415Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2416 if (CGM.getLangOpts().OpenMPSimd)
2417 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002418 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2419 isDeclareTargetDeclaration(VD);
2420 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2421 SmallString<64> PtrName;
2422 {
2423 llvm::raw_svector_ostream OS(PtrName);
2424 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2425 }
2426 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2427 if (!Ptr) {
2428 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2429 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2430 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002431 if (!CGM.getLangOpts().OpenMPIsDevice) {
2432 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2433 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2434 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2435 }
2436 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2437 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002438 }
2439 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2440 }
2441 return Address::invalid();
2442}
2443
Alexey Bataev97720002014-11-11 04:05:39 +00002444llvm::Constant *
2445CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002446 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2447 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002448 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002449 std::string Suffix = getName({"cache", ""});
2450 return getOrCreateInternalVariable(
2451 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002452}
2453
John McCall7f416cc2015-09-08 08:05:57 +00002454Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2455 const VarDecl *VD,
2456 Address VDAddr,
2457 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002458 if (CGM.getLangOpts().OpenMPUseTLS &&
2459 CGM.getContext().getTargetInfo().isTLSSupported())
2460 return VDAddr;
2461
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002462 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002463 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002464 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2465 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002466 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2467 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002468 return Address(CGF.EmitRuntimeCall(
2469 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2470 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002471}
2472
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002473void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002474 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002475 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2476 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2477 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002478 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002479 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002480 OMPLoc);
2481 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2482 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002483 llvm::Value *Args[] = {
2484 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2485 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002486 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002487 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002488}
2489
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002490llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002491 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002492 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002493 if (CGM.getLangOpts().OpenMPUseTLS &&
2494 CGM.getContext().getTargetInfo().isTLSSupported())
2495 return nullptr;
2496
Alexey Bataev97720002014-11-11 04:05:39 +00002497 VD = VD->getDefinition(CGM.getContext());
2498 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2499 ThreadPrivateWithDefinition.insert(VD);
2500 QualType ASTTy = VD->getType();
2501
2502 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002503 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002504 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2505 // Generate function that re-emits the declaration's initializer into the
2506 // threadprivate copy of the variable VD
2507 CodeGenFunction CtorCGF(CGM);
2508 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002509 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2510 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002511 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002512 Args.push_back(&Dst);
2513
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002514 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002515 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002516 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002517 std::string Name = getName({"__kmpc_global_ctor_", ""});
2518 llvm::Function *Fn =
2519 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002520 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002521 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002523 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002524 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002525 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002526 Arg = CtorCGF.Builder.CreateElementBitCast(
2527 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002528 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2529 /*IsInitializer=*/true);
2530 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002531 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002532 CGM.getContext().VoidPtrTy, Dst.getLocation());
2533 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2534 CtorCGF.FinishFunction();
2535 Ctor = Fn;
2536 }
2537 if (VD->getType().isDestructedType() != QualType::DK_none) {
2538 // Generate function that emits destructor call for the threadprivate copy
2539 // of the variable VD
2540 CodeGenFunction DtorCGF(CGM);
2541 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002542 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2543 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002544 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002545 Args.push_back(&Dst);
2546
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002547 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002548 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002549 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002550 std::string Name = getName({"__kmpc_global_dtor_", ""});
2551 llvm::Function *Fn =
2552 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002553 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002554 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002555 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002556 // Create a scope with an artificial location for the body of this function.
2557 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002558 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002559 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002560 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2561 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002562 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2563 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2564 DtorCGF.FinishFunction();
2565 Dtor = Fn;
2566 }
2567 // Do not emit init function if it is not required.
2568 if (!Ctor && !Dtor)
2569 return nullptr;
2570
2571 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002572 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2573 /*isVarArg=*/false)
2574 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002575 // Copying constructor for the threadprivate variable.
2576 // Must be NULL - reserved by runtime, but currently it requires that this
2577 // parameter is always NULL. Otherwise it fires assertion.
2578 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2579 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002580 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2581 /*isVarArg=*/false)
2582 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002583 Ctor = llvm::Constant::getNullValue(CtorTy);
2584 }
2585 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002586 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2587 /*isVarArg=*/false)
2588 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002589 Dtor = llvm::Constant::getNullValue(DtorTy);
2590 }
2591 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002592 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002593 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002594 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002595 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002596 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002597 CodeGenFunction InitCGF(CGM);
2598 FunctionArgList ArgList;
2599 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2600 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002601 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002602 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002603 InitCGF.FinishFunction();
2604 return InitFunction;
2605 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002606 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002607 }
2608 return nullptr;
2609}
2610
Alexey Bataev34f8a702018-03-28 14:28:54 +00002611/// \brief Obtain information that uniquely identifies a target entry. This
2612/// consists of the file and device IDs as well as line number associated with
2613/// the relevant entry source location.
2614static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2615 unsigned &DeviceID, unsigned &FileID,
2616 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002617 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002618
2619 // The loc should be always valid and have a file ID (the user cannot use
2620 // #pragma directives in macros)
2621
2622 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002623
2624 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2625 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2626
2627 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002628 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2629 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2630 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002631
2632 DeviceID = ID.getDevice();
2633 FileID = ID.getFile();
2634 LineNum = PLoc.getLine();
2635}
2636
2637bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2638 llvm::GlobalVariable *Addr,
2639 bool PerformInit) {
2640 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2641 isDeclareTargetDeclaration(VD);
2642 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2643 return false;
2644 VD = VD->getDefinition(CGM.getContext());
2645 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2646 return CGM.getLangOpts().OpenMPIsDevice;
2647
2648 QualType ASTTy = VD->getType();
2649
2650 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2651 // Produce the unique prefix to identify the new target regions. We use
2652 // the source location of the variable declaration which we know to not
2653 // conflict with any target region.
2654 unsigned DeviceID;
2655 unsigned FileID;
2656 unsigned Line;
2657 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2658 SmallString<128> Buffer, Out;
2659 {
2660 llvm::raw_svector_ostream OS(Buffer);
2661 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2662 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2663 }
2664
2665 const Expr *Init = VD->getAnyInitializer();
2666 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2667 llvm::Constant *Ctor;
2668 llvm::Constant *ID;
2669 if (CGM.getLangOpts().OpenMPIsDevice) {
2670 // Generate function that re-emits the declaration's initializer into
2671 // the threadprivate copy of the variable VD
2672 CodeGenFunction CtorCGF(CGM);
2673
2674 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2675 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2676 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2677 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2678 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2679 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2680 FunctionArgList(), Loc, Loc);
2681 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2682 CtorCGF.EmitAnyExprToMem(Init,
2683 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2684 Init->getType().getQualifiers(),
2685 /*IsInitializer=*/true);
2686 CtorCGF.FinishFunction();
2687 Ctor = Fn;
2688 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2689 } else {
2690 Ctor = new llvm::GlobalVariable(
2691 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2692 llvm::GlobalValue::PrivateLinkage,
2693 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2694 ID = Ctor;
2695 }
2696
2697 // Register the information for the entry associated with the constructor.
2698 Out.clear();
2699 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2700 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002701 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002702 }
2703 if (VD->getType().isDestructedType() != QualType::DK_none) {
2704 llvm::Constant *Dtor;
2705 llvm::Constant *ID;
2706 if (CGM.getLangOpts().OpenMPIsDevice) {
2707 // Generate function that emits destructor call for the threadprivate
2708 // copy of the variable VD
2709 CodeGenFunction DtorCGF(CGM);
2710
2711 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2712 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2713 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2714 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2715 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2716 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2717 FunctionArgList(), Loc, Loc);
2718 // Create a scope with an artificial location for the body of this
2719 // function.
2720 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2721 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2722 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2723 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2724 DtorCGF.FinishFunction();
2725 Dtor = Fn;
2726 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2727 } else {
2728 Dtor = new llvm::GlobalVariable(
2729 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2730 llvm::GlobalValue::PrivateLinkage,
2731 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2732 ID = Dtor;
2733 }
2734 // Register the information for the entry associated with the destructor.
2735 Out.clear();
2736 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2737 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002738 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002739 }
2740 return CGM.getLangOpts().OpenMPIsDevice;
2741}
2742
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002743Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2744 QualType VarType,
2745 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002746 std::string Suffix = getName({"artificial", ""});
2747 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002748 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002749 llvm::Value *GAddr =
2750 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002751 llvm::Value *Args[] = {
2752 emitUpdateLocation(CGF, SourceLocation()),
2753 getThreadID(CGF, SourceLocation()),
2754 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2755 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2756 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002757 getOrCreateInternalVariable(
2758 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002759 return Address(
2760 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2761 CGF.EmitRuntimeCall(
2762 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2763 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2764 CGM.getPointerAlign());
2765}
2766
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002767void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2768 const RegionCodeGenTy &ThenGen,
2769 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002770 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2771
2772 // If the condition constant folds and can be elided, try to avoid emitting
2773 // the condition and the dead arm of the if/else.
2774 bool CondConstant;
2775 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002776 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002777 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002778 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002779 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002780 return;
2781 }
2782
2783 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2784 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002785 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2786 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2787 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002788 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2789
2790 // Emit the 'then' code.
2791 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002792 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002793 CGF.EmitBranch(ContBlock);
2794 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002795 // There is no need to emit line number for unconditional branch.
2796 (void)ApplyDebugLocation::CreateEmpty(CGF);
2797 CGF.EmitBlock(ElseBlock);
2798 ElseGen(CGF);
2799 // There is no need to emit line number for unconditional branch.
2800 (void)ApplyDebugLocation::CreateEmpty(CGF);
2801 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002802 // Emit the continuation block for code after the if.
2803 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002804}
2805
Alexey Bataev1d677132015-04-22 13:57:31 +00002806void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2807 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002808 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002809 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002810 if (!CGF.HaveInsertPoint())
2811 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002812 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002813 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2814 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002815 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002816 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002817 llvm::Value *Args[] = {
2818 RTLoc,
2819 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002820 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002821 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2822 RealArgs.append(std::begin(Args), std::end(Args));
2823 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2824
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002825 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002826 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2827 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002828 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2829 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002830 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2831 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002832 // Build calls:
2833 // __kmpc_serialized_parallel(&Loc, GTid);
2834 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002835 CGF.EmitRuntimeCall(
2836 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002837
Alexey Bataev1d677132015-04-22 13:57:31 +00002838 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002839 Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002840 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2841 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002842 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002843 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2844 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2845 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2846 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002847 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002848
Alexey Bataev1d677132015-04-22 13:57:31 +00002849 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002850 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002851 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002852 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2853 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002854 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002855 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002856 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002857 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002858 RegionCodeGenTy ThenRCG(ThenGen);
2859 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002860 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002861}
2862
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002863// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002864// thread-ID variable (it is passed in a first argument of the outlined function
2865// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2866// regular serial code region, get thread ID by calling kmp_int32
2867// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2868// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002869Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2870 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002871 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002872 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002873 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002874 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002875
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002876 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2877 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002878 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002879 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002880 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002881 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002882
2883 return ThreadIDTemp;
2884}
2885
Alexey Bataev97720002014-11-11 04:05:39 +00002886llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002887CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002888 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002889 SmallString<256> Buffer;
2890 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002891 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002892 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002893 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002894 if (Elem.second) {
2895 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002896 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002897 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002898 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002899
David Blaikie13156b62014-11-19 03:06:06 +00002900 return Elem.second = new llvm::GlobalVariable(
2901 CGM.getModule(), Ty, /*IsConstant*/ false,
2902 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2903 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002904}
2905
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002906llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002907 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2908 std::string Name = getName({Prefix, "var"});
2909 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002910}
2911
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002912namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002913/// Common pre(post)-action for different OpenMP constructs.
2914class CommonActionTy final : public PrePostActionTy {
2915 llvm::Value *EnterCallee;
2916 ArrayRef<llvm::Value *> EnterArgs;
2917 llvm::Value *ExitCallee;
2918 ArrayRef<llvm::Value *> ExitArgs;
2919 bool Conditional;
2920 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002921
2922public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002923 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2924 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2925 bool Conditional = false)
2926 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2927 ExitArgs(ExitArgs), Conditional(Conditional) {}
2928 void Enter(CodeGenFunction &CGF) override {
2929 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2930 if (Conditional) {
2931 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2932 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2933 ContBlock = CGF.createBasicBlock("omp_if.end");
2934 // Generate the branch (If-stmt)
2935 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2936 CGF.EmitBlock(ThenBlock);
2937 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002938 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002939 void Done(CodeGenFunction &CGF) {
2940 // Emit the rest of blocks/branches
2941 CGF.EmitBranch(ContBlock);
2942 CGF.EmitBlock(ContBlock, true);
2943 }
2944 void Exit(CodeGenFunction &CGF) override {
2945 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002946 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002947};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002948} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002949
2950void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2951 StringRef CriticalName,
2952 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002953 SourceLocation Loc, const Expr *Hint) {
2954 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002955 // CriticalOpGen();
2956 // __kmpc_end_critical(ident_t *, gtid, Lock);
2957 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002958 if (!CGF.HaveInsertPoint())
2959 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002960 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2961 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002962 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2963 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002964 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002965 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2966 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2967 }
2968 CommonActionTy Action(
2969 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2970 : OMPRTL__kmpc_critical),
2971 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2972 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002973 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002974}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002975
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002976void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002977 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002978 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002979 if (!CGF.HaveInsertPoint())
2980 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002981 // if(__kmpc_master(ident_t *, gtid)) {
2982 // MasterOpGen();
2983 // __kmpc_end_master(ident_t *, gtid);
2984 // }
2985 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002986 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002987 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2988 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2989 /*Conditional=*/true);
2990 MasterOpGen.setAction(Action);
2991 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2992 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002993}
2994
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002995void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2996 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002997 if (!CGF.HaveInsertPoint())
2998 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002999 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3000 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003001 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003002 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003003 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003004 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3005 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003006}
3007
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003008void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3009 const RegionCodeGenTy &TaskgroupOpGen,
3010 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003011 if (!CGF.HaveInsertPoint())
3012 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003013 // __kmpc_taskgroup(ident_t *, gtid);
3014 // TaskgroupOpGen();
3015 // __kmpc_end_taskgroup(ident_t *, gtid);
3016 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003017 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3018 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3019 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3020 Args);
3021 TaskgroupOpGen.setAction(Action);
3022 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003023}
3024
John McCall7f416cc2015-09-08 08:05:57 +00003025/// Given an array of pointers to variables, project the address of a
3026/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003027static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3028 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003029 // Pull out the pointer to the variable.
3030 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003031 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003032 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3033
3034 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003035 Addr = CGF.Builder.CreateElementBitCast(
3036 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003037 return Addr;
3038}
3039
Alexey Bataeva63048e2015-03-23 06:18:07 +00003040static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003041 CodeGenModule &CGM, llvm::Type *ArgsType,
3042 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003043 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3044 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003045 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003046 // void copy_func(void *LHSArg, void *RHSArg);
3047 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003048 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3049 ImplicitParamDecl::Other);
3050 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3051 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003052 Args.push_back(&LHSArg);
3053 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003054 const auto &CGFI =
3055 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003056 std::string Name =
3057 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3058 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3059 llvm::GlobalValue::InternalLinkage, Name,
3060 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003061 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003062 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003063 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003064 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003065 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003066 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003067 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3068 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3069 ArgsType), CGF.getPointerAlign());
3070 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3071 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3072 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003073 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3074 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3075 // ...
3076 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003077 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003078 const auto *DestVar =
3079 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003080 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3081
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003082 const auto *SrcVar =
3083 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003084 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3085
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003086 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003087 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003088 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003089 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003090 CGF.FinishFunction();
3091 return Fn;
3092}
3093
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003094void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003095 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003096 SourceLocation Loc,
3097 ArrayRef<const Expr *> CopyprivateVars,
3098 ArrayRef<const Expr *> SrcExprs,
3099 ArrayRef<const Expr *> DstExprs,
3100 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003101 if (!CGF.HaveInsertPoint())
3102 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003103 assert(CopyprivateVars.size() == SrcExprs.size() &&
3104 CopyprivateVars.size() == DstExprs.size() &&
3105 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003106 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003107 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003108 // if(__kmpc_single(ident_t *, gtid)) {
3109 // SingleOpGen();
3110 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003111 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003112 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003113 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3114 // <copy_func>, did_it);
3115
John McCall7f416cc2015-09-08 08:05:57 +00003116 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003117 if (!CopyprivateVars.empty()) {
3118 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003119 QualType KmpInt32Ty =
3120 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003121 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003122 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003123 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003124 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003125 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003126 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3127 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3128 /*Conditional=*/true);
3129 SingleOpGen.setAction(Action);
3130 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3131 if (DidIt.isValid()) {
3132 // did_it = 1;
3133 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3134 }
3135 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003136 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3137 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003138 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003139 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003140 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003141 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3142 /*IndexTypeQuals=*/0);
3143 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003144 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003145 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3146 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003147 Address Elem = CGF.Builder.CreateConstArrayGEP(
3148 CopyprivateList, I, CGF.getPointerSize());
3149 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003150 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003151 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3152 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003153 }
3154 // Build function that copies private values from single region to all other
3155 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003156 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003157 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003158 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003159 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003160 Address CL =
3161 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3162 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003163 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003164 llvm::Value *Args[] = {
3165 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3166 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003167 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003168 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003169 CpyFn, // void (*) (void *, void *) <copy_func>
3170 DidItVal // i32 did_it
3171 };
3172 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3173 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003174}
3175
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003176void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3177 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003178 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003179 if (!CGF.HaveInsertPoint())
3180 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003181 // __kmpc_ordered(ident_t *, gtid);
3182 // OrderedOpGen();
3183 // __kmpc_end_ordered(ident_t *, gtid);
3184 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003185 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003186 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003187 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3188 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3189 Args);
3190 OrderedOpGen.setAction(Action);
3191 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3192 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003193 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003194 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003195}
3196
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003197void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003198 OpenMPDirectiveKind Kind, bool EmitChecks,
3199 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003200 if (!CGF.HaveInsertPoint())
3201 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003202 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003203 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003204 unsigned Flags;
3205 if (Kind == OMPD_for)
3206 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3207 else if (Kind == OMPD_sections)
3208 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3209 else if (Kind == OMPD_single)
3210 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3211 else if (Kind == OMPD_barrier)
3212 Flags = OMP_IDENT_BARRIER_EXPL;
3213 else
3214 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003215 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3216 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003217 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3218 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003219 if (auto *OMPRegionInfo =
3220 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003221 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003222 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003223 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003224 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003225 // if (__kmpc_cancel_barrier()) {
3226 // exit from construct;
3227 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003228 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3229 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3230 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003231 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3232 CGF.EmitBlock(ExitBB);
3233 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003234 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003235 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003236 CGF.EmitBranchThroughCleanup(CancelDestination);
3237 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3238 }
3239 return;
3240 }
3241 }
3242 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003243}
3244
Alexander Musmanc6388682014-12-15 07:07:06 +00003245/// \brief Map the OpenMP loop schedule to the runtime enumeration.
3246static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003247 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003248 switch (ScheduleKind) {
3249 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003250 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3251 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003252 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003253 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003254 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003255 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003256 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003257 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3258 case OMPC_SCHEDULE_auto:
3259 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003260 case OMPC_SCHEDULE_unknown:
3261 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003262 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003263 }
3264 llvm_unreachable("Unexpected runtime schedule");
3265}
3266
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003267/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3268static OpenMPSchedType
3269getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3270 // only static is allowed for dist_schedule
3271 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3272}
3273
Alexander Musmanc6388682014-12-15 07:07:06 +00003274bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3275 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003276 OpenMPSchedType Schedule =
3277 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003278 return Schedule == OMP_sch_static;
3279}
3280
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003281bool CGOpenMPRuntime::isStaticNonchunked(
3282 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003283 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003284 return Schedule == OMP_dist_sch_static;
3285}
3286
3287
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003288bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003289 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003290 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003291 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3292 return Schedule != OMP_sch_static;
3293}
3294
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003295static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3296 OpenMPScheduleClauseModifier M1,
3297 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003298 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003299 switch (M1) {
3300 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003301 Modifier = OMP_sch_modifier_monotonic;
3302 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003303 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003304 Modifier = OMP_sch_modifier_nonmonotonic;
3305 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003306 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003307 if (Schedule == OMP_sch_static_chunked)
3308 Schedule = OMP_sch_static_balanced_chunked;
3309 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003310 case OMPC_SCHEDULE_MODIFIER_last:
3311 case OMPC_SCHEDULE_MODIFIER_unknown:
3312 break;
3313 }
3314 switch (M2) {
3315 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003316 Modifier = OMP_sch_modifier_monotonic;
3317 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003318 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003319 Modifier = OMP_sch_modifier_nonmonotonic;
3320 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003321 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003322 if (Schedule == OMP_sch_static_chunked)
3323 Schedule = OMP_sch_static_balanced_chunked;
3324 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003325 case OMPC_SCHEDULE_MODIFIER_last:
3326 case OMPC_SCHEDULE_MODIFIER_unknown:
3327 break;
3328 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003329 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003330}
3331
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003332void CGOpenMPRuntime::emitForDispatchInit(
3333 CodeGenFunction &CGF, SourceLocation Loc,
3334 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3335 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003336 if (!CGF.HaveInsertPoint())
3337 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003338 OpenMPSchedType Schedule = getRuntimeSchedule(
3339 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003340 assert(Ordered ||
3341 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003342 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3343 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003344 // Call __kmpc_dispatch_init(
3345 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3346 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3347 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003348
John McCall7f416cc2015-09-08 08:05:57 +00003349 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003350 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3351 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003352 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003353 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3354 CGF.Builder.getInt32(addMonoNonMonoModifier(
3355 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003356 DispatchValues.LB, // Lower
3357 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003358 CGF.Builder.getIntN(IVSize, 1), // Stride
3359 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003360 };
3361 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3362}
3363
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003364static void emitForStaticInitCall(
3365 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3366 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3367 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003368 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003369 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003370 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003371
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003372 assert(!Values.Ordered);
3373 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3374 Schedule == OMP_sch_static_balanced_chunked ||
3375 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3376 Schedule == OMP_dist_sch_static ||
3377 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003378
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003379 // Call __kmpc_for_static_init(
3380 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3381 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3382 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3383 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3384 llvm::Value *Chunk = Values.Chunk;
3385 if (Chunk == nullptr) {
3386 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3387 Schedule == OMP_dist_sch_static) &&
3388 "expected static non-chunked schedule");
3389 // If the Chunk was not specified in the clause - use default value 1.
3390 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3391 } else {
3392 assert((Schedule == OMP_sch_static_chunked ||
3393 Schedule == OMP_sch_static_balanced_chunked ||
3394 Schedule == OMP_ord_static_chunked ||
3395 Schedule == OMP_dist_sch_static_chunked) &&
3396 "expected static chunked schedule");
3397 }
3398 llvm::Value *Args[] = {
3399 UpdateLocation,
3400 ThreadId,
3401 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3402 M2)), // Schedule type
3403 Values.IL.getPointer(), // &isLastIter
3404 Values.LB.getPointer(), // &LB
3405 Values.UB.getPointer(), // &UB
3406 Values.ST.getPointer(), // &Stride
3407 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3408 Chunk // Chunk
3409 };
3410 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003411}
3412
John McCall7f416cc2015-09-08 08:05:57 +00003413void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3414 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003415 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003416 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003417 const StaticRTInput &Values) {
3418 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3419 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3420 assert(isOpenMPWorksharingDirective(DKind) &&
3421 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003422 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003423 isOpenMPLoopDirective(DKind)
3424 ? OMP_IDENT_WORK_LOOP
3425 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003426 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3427 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003428 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003429 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003430 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003431}
John McCall7f416cc2015-09-08 08:05:57 +00003432
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003433void CGOpenMPRuntime::emitDistributeStaticInit(
3434 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003435 OpenMPDistScheduleClauseKind SchedKind,
3436 const CGOpenMPRuntime::StaticRTInput &Values) {
3437 OpenMPSchedType ScheduleNum =
3438 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003439 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003440 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003441 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3442 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003443 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003444 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3445 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003446 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003447}
3448
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003449void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003450 SourceLocation Loc,
3451 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003452 if (!CGF.HaveInsertPoint())
3453 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003454 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003455 llvm::Value *Args[] = {
3456 emitUpdateLocation(CGF, Loc,
3457 isOpenMPDistributeDirective(DKind)
3458 ? OMP_IDENT_WORK_DISTRIBUTE
3459 : isOpenMPLoopDirective(DKind)
3460 ? OMP_IDENT_WORK_LOOP
3461 : OMP_IDENT_WORK_SECTIONS),
3462 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003463 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3464 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003465}
3466
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003467void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3468 SourceLocation Loc,
3469 unsigned IVSize,
3470 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003471 if (!CGF.HaveInsertPoint())
3472 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003473 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003474 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003475 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3476}
3477
Alexander Musman92bdaab2015-03-12 13:37:50 +00003478llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3479 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003480 bool IVSigned, Address IL,
3481 Address LB, Address UB,
3482 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003483 // Call __kmpc_dispatch_next(
3484 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3485 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3486 // kmp_int[32|64] *p_stride);
3487 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003488 emitUpdateLocation(CGF, Loc),
3489 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003490 IL.getPointer(), // &isLastIter
3491 LB.getPointer(), // &Lower
3492 UB.getPointer(), // &Upper
3493 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003494 };
3495 llvm::Value *Call =
3496 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3497 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003498 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003499 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003500}
3501
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003502void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3503 llvm::Value *NumThreads,
3504 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003505 if (!CGF.HaveInsertPoint())
3506 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003507 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3508 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003509 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003510 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003511 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3512 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003513}
3514
Alexey Bataev7f210c62015-06-18 13:40:03 +00003515void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3516 OpenMPProcBindClauseKind ProcBind,
3517 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003518 if (!CGF.HaveInsertPoint())
3519 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003520 // Constants for proc bind value accepted by the runtime.
3521 enum ProcBindTy {
3522 ProcBindFalse = 0,
3523 ProcBindTrue,
3524 ProcBindMaster,
3525 ProcBindClose,
3526 ProcBindSpread,
3527 ProcBindIntel,
3528 ProcBindDefault
3529 } RuntimeProcBind;
3530 switch (ProcBind) {
3531 case OMPC_PROC_BIND_master:
3532 RuntimeProcBind = ProcBindMaster;
3533 break;
3534 case OMPC_PROC_BIND_close:
3535 RuntimeProcBind = ProcBindClose;
3536 break;
3537 case OMPC_PROC_BIND_spread:
3538 RuntimeProcBind = ProcBindSpread;
3539 break;
3540 case OMPC_PROC_BIND_unknown:
3541 llvm_unreachable("Unsupported proc_bind value.");
3542 }
3543 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3544 llvm::Value *Args[] = {
3545 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3546 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3547 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3548}
3549
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003550void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3551 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003552 if (!CGF.HaveInsertPoint())
3553 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003554 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003555 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3556 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003557}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003558
Alexey Bataev62b63b12015-03-10 07:28:44 +00003559namespace {
3560/// \brief Indexes of fields for type kmp_task_t.
3561enum KmpTaskTFields {
3562 /// \brief List of shared variables.
3563 KmpTaskTShareds,
3564 /// \brief Task routine.
3565 KmpTaskTRoutine,
3566 /// \brief Partition id for the untied tasks.
3567 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003568 /// Function with call of destructors for private variables.
3569 Data1,
3570 /// Task priority.
3571 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003572 /// (Taskloops only) Lower bound.
3573 KmpTaskTLowerBound,
3574 /// (Taskloops only) Upper bound.
3575 KmpTaskTUpperBound,
3576 /// (Taskloops only) Stride.
3577 KmpTaskTStride,
3578 /// (Taskloops only) Is last iteration flag.
3579 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003580 /// (Taskloops only) Reduction data.
3581 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003582};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003583} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003584
Samuel Antaoee8fb302016-01-06 13:42:12 +00003585bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003586 return OffloadEntriesTargetRegion.empty() &&
3587 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003588}
3589
3590/// \brief Initialize target region entry.
3591void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3592 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3593 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003594 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003595 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3596 "only required for the device "
3597 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003598 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003599 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003600 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003601 ++OffloadingEntriesNum;
3602}
3603
3604void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3605 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3606 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003607 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003608 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003609 // If we are emitting code for a target, the entry is already initialized,
3610 // only has to be registered.
3611 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003612 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3613 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3614 DiagnosticsEngine::Error,
3615 "Unable to find target region on line '%0' in the device code.");
3616 CGM.getDiags().Report(DiagID) << LineNum;
3617 return;
3618 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003619 auto &Entry =
3620 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003621 assert(Entry.isValid() && "Entry not initialized!");
3622 Entry.setAddress(Addr);
3623 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003624 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003625 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003626 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003627 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003628 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003629 }
3630}
3631
3632bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003633 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3634 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003635 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3636 if (PerDevice == OffloadEntriesTargetRegion.end())
3637 return false;
3638 auto PerFile = PerDevice->second.find(FileID);
3639 if (PerFile == PerDevice->second.end())
3640 return false;
3641 auto PerParentName = PerFile->second.find(ParentName);
3642 if (PerParentName == PerFile->second.end())
3643 return false;
3644 auto PerLine = PerParentName->second.find(LineNum);
3645 if (PerLine == PerParentName->second.end())
3646 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003647 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003648 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003649 return false;
3650 return true;
3651}
3652
3653void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3654 const OffloadTargetRegionEntryInfoActTy &Action) {
3655 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003656 for (const auto &D : OffloadEntriesTargetRegion)
3657 for (const auto &F : D.second)
3658 for (const auto &P : F.second)
3659 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003660 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003661}
3662
Alexey Bataev03f270c2018-03-30 18:31:07 +00003663void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3664 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3665 OMPTargetGlobalVarEntryKind Flags,
3666 unsigned Order) {
3667 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3668 "only required for the device "
3669 "code generation.");
3670 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3671 ++OffloadingEntriesNum;
3672}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003673
Alexey Bataev03f270c2018-03-30 18:31:07 +00003674void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3675 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3676 CharUnits VarSize,
3677 OMPTargetGlobalVarEntryKind Flags,
3678 llvm::GlobalValue::LinkageTypes Linkage) {
3679 if (CGM.getLangOpts().OpenMPIsDevice) {
3680 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3681 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3682 "Entry not initialized!");
3683 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3684 "Resetting with the new address.");
3685 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3686 return;
3687 Entry.setAddress(Addr);
3688 Entry.setVarSize(VarSize);
3689 Entry.setLinkage(Linkage);
3690 } else {
3691 if (hasDeviceGlobalVarEntryInfo(VarName))
3692 return;
3693 OffloadEntriesDeviceGlobalVar.try_emplace(
3694 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3695 ++OffloadingEntriesNum;
3696 }
3697}
3698
3699void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3700 actOnDeviceGlobalVarEntriesInfo(
3701 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3702 // Scan all target region entries and perform the provided action.
3703 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3704 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003705}
3706
3707llvm::Function *
3708CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003709 // If we don't have entries or if we are emitting code for the device, we
3710 // don't need to do anything.
3711 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3712 return nullptr;
3713
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003714 llvm::Module &M = CGM.getModule();
3715 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003716
3717 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003718 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003719
3720 // We should be creating an offloading descriptor only if there are devices
3721 // specified.
3722 assert(!Devices.empty() && "No OpenMP offloading devices??");
3723
3724 // Create the external variables that will point to the begin and end of the
3725 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003726 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003727 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003728 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003729 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003730 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003731 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003732 EntriesBeginName);
3733 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3734 auto *HostEntriesEnd =
3735 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3736 llvm::GlobalValue::ExternalLinkage,
3737 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003738
3739 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003740 auto *DeviceImageTy = cast<llvm::StructType>(
3741 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003742 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003743 ConstantArrayBuilder DeviceImagesEntries =
3744 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003745
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003746 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003747 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003748 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003749 auto *ImgBegin = new llvm::GlobalVariable(
3750 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003751 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3752 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003753 auto *ImgEnd = new llvm::GlobalVariable(
3754 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003755 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003756
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003757 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3758 HostEntriesEnd};
3759 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3760 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003761 }
3762
3763 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003764 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003765 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003766 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3767 CGM.getPointerAlign(),
3768 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003769 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003770
3771 // This is a Zero array to be used in the creation of the constant expressions
3772 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3773 llvm::Constant::getNullValue(CGM.Int32Ty)};
3774
3775 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003776 llvm::Constant *Data[] = {
3777 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3778 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3779 DeviceImages, Index),
3780 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003781 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003782 llvm::GlobalVariable *Desc = createConstantGlobalStruct(
Alexey Bataev18fa2322018-05-02 14:20:50 +00003783 CGM, getTgtBinaryDescriptorQTy(), Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003784
3785 // Emit code to register or unregister the descriptor at execution
3786 // startup or closing, respectively.
3787
Alexey Bataev03f270c2018-03-30 18:31:07 +00003788 llvm::Function *UnRegFn;
3789 {
3790 FunctionArgList Args;
3791 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3792 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003793
Alexey Bataev03f270c2018-03-30 18:31:07 +00003794 CodeGenFunction CGF(CGM);
3795 // Disable debug info for global (de-)initializer because they are not part
3796 // of some particular construct.
3797 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003798 const auto &FI =
3799 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3800 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003801 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3802 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003803 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3804 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3805 Desc);
3806 CGF.FinishFunction();
3807 }
3808 llvm::Function *RegFn;
3809 {
3810 CodeGenFunction CGF(CGM);
3811 // Disable debug info for global (de-)initializer because they are not part
3812 // of some particular construct.
3813 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003814 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003815 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003816 std::string Descriptor = getName({"omp_offloading", "descriptor_reg"});
3817 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003818 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3819 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3820 // Create a variable to drive the registration and unregistration of the
3821 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3822 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3823 SourceLocation(), nullptr, C.CharTy,
3824 ImplicitParamDecl::Other);
3825 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3826 CGF.FinishFunction();
3827 }
George Rokos29d0f002017-05-27 03:03:13 +00003828 if (CGM.supportsCOMDAT()) {
3829 // It is sufficient to call registration function only once, so create a
3830 // COMDAT group for registration/unregistration functions and associated
3831 // data. That would reduce startup time and code size. Registration
3832 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003833 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003834 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3835 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3836 RegFn->setComdat(ComdatKey);
3837 UnRegFn->setComdat(ComdatKey);
3838 DeviceImages->setComdat(ComdatKey);
3839 Desc->setComdat(ComdatKey);
3840 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003841 return RegFn;
3842}
3843
Alexey Bataev03f270c2018-03-30 18:31:07 +00003844void CGOpenMPRuntime::createOffloadEntry(
3845 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3846 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003847 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003848 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003849 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003850
3851 // Create constant string with the name.
3852 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3853
Alexey Bataev18fa2322018-05-02 14:20:50 +00003854 std::string StringName = getName({"omp_offloading", "entry_name"});
3855 auto *Str = new llvm::GlobalVariable(
3856 M, StrPtrInit->getType(), /*isConstant=*/true,
3857 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003858 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003859
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003860 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3861 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3862 llvm::ConstantInt::get(CGM.SizeTy, Size),
3863 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3864 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003865 std::string EntryName = getName({"omp_offloading", "entry", ""});
Alexey Bataev9a700172018-05-08 14:16:57 +00003866 llvm::GlobalVariable *Entry = createConstantGlobalStruct(
3867 CGM, getTgtOffloadEntryQTy(), Data, Twine(EntryName).concat(Name),
3868 llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003869
3870 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003871 std::string Section = getName({"omp_offloading", "entries"});
3872 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003873}
3874
3875void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3876 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003877 // can easily figure out what to emit. The produced metadata looks like
3878 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003879 //
3880 // !omp_offload.info = !{!1, ...}
3881 //
3882 // Right now we only generate metadata for function that contain target
3883 // regions.
3884
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003885 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003886 if (OffloadEntriesInfoManager.empty())
3887 return;
3888
3889 llvm::Module &M = CGM.getModule();
3890 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003891 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003892 OrderedEntries(OffloadEntriesInfoManager.size());
3893
Simon Pilgrim2c518802017-03-30 14:13:19 +00003894 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003895 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003896 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003897 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003898 };
3899
Alexey Bataev03f270c2018-03-30 18:31:07 +00003900 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3901
3902 // Create the offloading info metadata node.
3903 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003904
3905 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003906 auto &&TargetRegionMetadataEmitter =
3907 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3908 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3909 unsigned Line,
3910 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3911 // Generate metadata for target regions. Each entry of this metadata
3912 // contains:
3913 // - Entry 0 -> Kind of this type of metadata (0).
3914 // - Entry 1 -> Device ID of the file where the entry was identified.
3915 // - Entry 2 -> File ID of the file where the entry was identified.
3916 // - Entry 3 -> Mangled name of the function where the entry was
3917 // identified.
3918 // - Entry 4 -> Line in the file where the entry was identified.
3919 // - Entry 5 -> Order the entry was created.
3920 // The first element of the metadata node is the kind.
3921 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3922 GetMDInt(FileID), GetMDString(ParentName),
3923 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003924
Alexey Bataev03f270c2018-03-30 18:31:07 +00003925 // Save this entry in the right position of the ordered entries array.
3926 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003927
Alexey Bataev03f270c2018-03-30 18:31:07 +00003928 // Add metadata to the named metadata node.
3929 MD->addOperand(llvm::MDNode::get(C, Ops));
3930 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003931
3932 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3933 TargetRegionMetadataEmitter);
3934
Alexey Bataev03f270c2018-03-30 18:31:07 +00003935 // Create function that emits metadata for each device global variable entry;
3936 auto &&DeviceGlobalVarMetadataEmitter =
3937 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3938 MD](StringRef MangledName,
3939 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3940 &E) {
3941 // Generate metadata for global variables. Each entry of this metadata
3942 // contains:
3943 // - Entry 0 -> Kind of this type of metadata (1).
3944 // - Entry 1 -> Mangled name of the variable.
3945 // - Entry 2 -> Declare target kind.
3946 // - Entry 3 -> Order the entry was created.
3947 // The first element of the metadata node is the kind.
3948 llvm::Metadata *Ops[] = {
3949 GetMDInt(E.getKind()), GetMDString(MangledName),
3950 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3951
3952 // Save this entry in the right position of the ordered entries array.
3953 OrderedEntries[E.getOrder()] = &E;
3954
3955 // Add metadata to the named metadata node.
3956 MD->addOperand(llvm::MDNode::get(C, Ops));
3957 };
3958
3959 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3960 DeviceGlobalVarMetadataEmitter);
3961
3962 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003963 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003964 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003965 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3966 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003967 if (!CE->getID() || !CE->getAddress()) {
3968 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3969 DiagnosticsEngine::Error,
3970 "Offloading entry for target region is incorect: either the "
3971 "address or the ID is invalid.");
3972 CGM.getDiags().Report(DiagID);
3973 continue;
3974 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00003975 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003976 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3977 } else if (const auto *CE =
3978 dyn_cast<OffloadEntriesInfoManagerTy::
3979 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003980 if (!CE->getAddress()) {
3981 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3982 DiagnosticsEngine::Error,
3983 "Offloading entry for declare target varible is inccorect: the "
3984 "address is invalid.");
3985 CGM.getDiags().Report(DiagID);
3986 continue;
3987 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003988 createOffloadEntry(CE->getAddress(), CE->getAddress(),
3989 CE->getVarSize().getQuantity(), CE->getFlags(),
3990 CE->getLinkage());
3991 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003992 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003993 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003994 }
3995}
3996
3997/// \brief Loads all the offload entries information from the host IR
3998/// metadata.
3999void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4000 // If we are in target mode, load the metadata from the host IR. This code has
4001 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4002
4003 if (!CGM.getLangOpts().OpenMPIsDevice)
4004 return;
4005
4006 if (CGM.getLangOpts().OMPHostIRFile.empty())
4007 return;
4008
4009 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004010 if (auto EC = Buf.getError()) {
4011 CGM.getDiags().Report(diag::err_cannot_open_file)
4012 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004013 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004014 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004015
4016 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004017 auto ME = expectedToErrorOrAndEmitErrors(
4018 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004019
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004020 if (auto EC = ME.getError()) {
4021 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4022 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4023 CGM.getDiags().Report(DiagID)
4024 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004025 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004026 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004027
4028 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4029 if (!MD)
4030 return;
4031
George Burgess IV00f70bd2018-03-01 05:43:23 +00004032 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004033 auto &&GetMDInt = [MN](unsigned Idx) {
4034 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004035 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4036 };
4037
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004038 auto &&GetMDString = [MN](unsigned Idx) {
4039 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004040 return V->getString();
4041 };
4042
Alexey Bataev03f270c2018-03-30 18:31:07 +00004043 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004044 default:
4045 llvm_unreachable("Unexpected metadata!");
4046 break;
4047 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004048 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004049 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004050 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4051 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4052 /*Order=*/GetMDInt(5));
4053 break;
4054 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4055 OffloadingEntryInfoDeviceGlobalVar:
4056 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4057 /*MangledName=*/GetMDString(1),
4058 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4059 /*Flags=*/GetMDInt(2)),
4060 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004061 break;
4062 }
4063 }
4064}
4065
Alexey Bataev62b63b12015-03-10 07:28:44 +00004066void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4067 if (!KmpRoutineEntryPtrTy) {
4068 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004069 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004070 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4071 FunctionProtoType::ExtProtoInfo EPI;
4072 KmpRoutineEntryPtrQTy = C.getPointerType(
4073 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4074 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4075 }
4076}
4077
Samuel Antaoee8fb302016-01-06 13:42:12 +00004078QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004079 // Make sure the type of the entry is already created. This is the type we
4080 // have to create:
4081 // struct __tgt_offload_entry{
4082 // void *addr; // Pointer to the offload entry info.
4083 // // (function or global)
4084 // char *name; // Name of the function or global.
4085 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004086 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4087 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004088 // };
4089 if (TgtOffloadEntryQTy.isNull()) {
4090 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004091 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004092 RD->startDefinition();
4093 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4094 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4095 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004096 addFieldToRecordDecl(
4097 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4098 addFieldToRecordDecl(
4099 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004100 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004101 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004102 TgtOffloadEntryQTy = C.getRecordType(RD);
4103 }
4104 return TgtOffloadEntryQTy;
4105}
4106
4107QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4108 // These are the types we need to build:
4109 // struct __tgt_device_image{
4110 // void *ImageStart; // Pointer to the target code start.
4111 // void *ImageEnd; // Pointer to the target code end.
4112 // // We also add the host entries to the device image, as it may be useful
4113 // // for the target runtime to have access to that information.
4114 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4115 // // the entries.
4116 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4117 // // entries (non inclusive).
4118 // };
4119 if (TgtDeviceImageQTy.isNull()) {
4120 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004121 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004122 RD->startDefinition();
4123 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4124 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4125 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4126 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4127 RD->completeDefinition();
4128 TgtDeviceImageQTy = C.getRecordType(RD);
4129 }
4130 return TgtDeviceImageQTy;
4131}
4132
4133QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4134 // struct __tgt_bin_desc{
4135 // int32_t NumDevices; // Number of devices supported.
4136 // __tgt_device_image *DeviceImages; // Arrays of device images
4137 // // (one per device).
4138 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4139 // // entries.
4140 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4141 // // entries (non inclusive).
4142 // };
4143 if (TgtBinaryDescriptorQTy.isNull()) {
4144 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004145 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004146 RD->startDefinition();
4147 addFieldToRecordDecl(
4148 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4149 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4150 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4151 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4152 RD->completeDefinition();
4153 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4154 }
4155 return TgtBinaryDescriptorQTy;
4156}
4157
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004158namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004159struct PrivateHelpersTy {
4160 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4161 const VarDecl *PrivateElemInit)
4162 : Original(Original), PrivateCopy(PrivateCopy),
4163 PrivateElemInit(PrivateElemInit) {}
4164 const VarDecl *Original;
4165 const VarDecl *PrivateCopy;
4166 const VarDecl *PrivateElemInit;
4167};
4168typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004169} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004170
Alexey Bataev9e034042015-05-05 04:05:12 +00004171static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004172createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004173 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004174 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004175 // Build struct .kmp_privates_t. {
4176 // /* private vars */
4177 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004178 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004179 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004180 for (const auto &Pair : Privates) {
4181 const VarDecl *VD = Pair.second.Original;
4182 QualType Type = VD->getType().getNonReferenceType();
4183 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004184 if (VD->hasAttrs()) {
4185 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4186 E(VD->getAttrs().end());
4187 I != E; ++I)
4188 FD->addAttr(*I);
4189 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004190 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004191 RD->completeDefinition();
4192 return RD;
4193 }
4194 return nullptr;
4195}
4196
Alexey Bataev9e034042015-05-05 04:05:12 +00004197static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004198createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4199 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004200 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004201 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004202 // Build struct kmp_task_t {
4203 // void * shareds;
4204 // kmp_routine_entry_t routine;
4205 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004206 // kmp_cmplrdata_t data1;
4207 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004208 // For taskloops additional fields:
4209 // kmp_uint64 lb;
4210 // kmp_uint64 ub;
4211 // kmp_int64 st;
4212 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004213 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004214 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004215 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004216 UD->startDefinition();
4217 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4218 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4219 UD->completeDefinition();
4220 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004221 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004222 RD->startDefinition();
4223 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4224 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4225 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004226 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4227 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004228 if (isOpenMPTaskLoopDirective(Kind)) {
4229 QualType KmpUInt64Ty =
4230 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4231 QualType KmpInt64Ty =
4232 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4233 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4234 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4235 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4236 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004237 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004238 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004239 RD->completeDefinition();
4240 return RD;
4241}
4242
4243static RecordDecl *
4244createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004245 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004246 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004247 // Build struct kmp_task_t_with_privates {
4248 // kmp_task_t task_data;
4249 // .kmp_privates_t. privates;
4250 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004251 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004252 RD->startDefinition();
4253 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004254 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004255 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004256 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004257 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004258}
4259
4260/// \brief Emit a proxy function which accepts kmp_task_t as the second
4261/// argument.
4262/// \code
4263/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004264/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004265/// For taskloops:
4266/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004267/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004268/// return 0;
4269/// }
4270/// \endcode
4271static llvm::Value *
4272emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004273 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4274 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004275 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004276 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4277 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004278 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004279 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004280 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4281 ImplicitParamDecl::Other);
4282 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4283 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4284 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004285 Args.push_back(&GtidArg);
4286 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004287 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004288 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004289 llvm::FunctionType *TaskEntryTy =
4290 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004291 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4292 auto *TaskEntry = llvm::Function::Create(
4293 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004294 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004295 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004296 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004297 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4298 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004299
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004300 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004301 // tt,
4302 // For taskloops:
4303 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4304 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004305 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004306 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004307 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4308 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4309 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004310 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004311 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004312 LValue Base =
4313 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004314 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004315 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004316 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4317 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004318
4319 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004320 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4321 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004322 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004323 CGF.ConvertTypeForMem(SharedsPtrTy));
4324
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004325 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4326 llvm::Value *PrivatesParam;
4327 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004328 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004329 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004330 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004331 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004332 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004333 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004334
Alexey Bataev7292c292016-04-25 12:22:29 +00004335 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4336 TaskPrivatesMap,
4337 CGF.Builder
4338 .CreatePointerBitCastOrAddrSpaceCast(
4339 TDBase.getAddress(), CGF.VoidPtrTy)
4340 .getPointer()};
4341 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4342 std::end(CommonArgs));
4343 if (isOpenMPTaskLoopDirective(Kind)) {
4344 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004345 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4346 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004347 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004348 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4349 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004350 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004351 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4352 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004353 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004354 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4355 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004356 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004357 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4358 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004359 CallArgs.push_back(LBParam);
4360 CallArgs.push_back(UBParam);
4361 CallArgs.push_back(StParam);
4362 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004363 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004364 }
4365 CallArgs.push_back(SharedsParam);
4366
Alexey Bataev3c595a62017-08-14 15:01:03 +00004367 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4368 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004369 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4370 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004371 CGF.FinishFunction();
4372 return TaskEntry;
4373}
4374
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004375static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4376 SourceLocation Loc,
4377 QualType KmpInt32Ty,
4378 QualType KmpTaskTWithPrivatesPtrQTy,
4379 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004380 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004381 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004382 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4383 ImplicitParamDecl::Other);
4384 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4385 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4386 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004387 Args.push_back(&GtidArg);
4388 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004389 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004390 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004391 llvm::FunctionType *DestructorFnTy =
4392 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004393 std::string Name =
4394 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004395 auto *DestructorFn =
4396 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004397 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004398 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004399 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004400 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004401 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004402 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004403 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004404
Alexey Bataev31300ed2016-02-04 11:27:03 +00004405 LValue Base = CGF.EmitLoadOfPointerLValue(
4406 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4407 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004408 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004409 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4410 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004411 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004412 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004413 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004414 if (QualType::DestructionKind DtorKind =
4415 Field->getType().isDestructedType()) {
4416 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004417 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4418 }
4419 }
4420 CGF.FinishFunction();
4421 return DestructorFn;
4422}
4423
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004424/// \brief Emit a privates mapping function for correct handling of private and
4425/// firstprivate variables.
4426/// \code
4427/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4428/// **noalias priv1,..., <tyn> **noalias privn) {
4429/// *priv1 = &.privates.priv1;
4430/// ...;
4431/// *privn = &.privates.privn;
4432/// }
4433/// \endcode
4434static llvm::Value *
4435emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004436 ArrayRef<const Expr *> PrivateVars,
4437 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004438 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004439 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004440 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004441 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004442 FunctionArgList Args;
4443 ImplicitParamDecl TaskPrivatesArg(
4444 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004445 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4446 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004447 Args.push_back(&TaskPrivatesArg);
4448 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4449 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004450 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004451 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004452 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4453 C.getPointerType(C.getPointerType(E->getType()))
4454 .withConst()
4455 .withRestrict(),
4456 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004457 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004458 PrivateVarsPos[VD] = Counter;
4459 ++Counter;
4460 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004461 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004462 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004463 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4464 C.getPointerType(C.getPointerType(E->getType()))
4465 .withConst()
4466 .withRestrict(),
4467 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004468 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004469 PrivateVarsPos[VD] = Counter;
4470 ++Counter;
4471 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004472 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004473 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004474 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4475 C.getPointerType(C.getPointerType(E->getType()))
4476 .withConst()
4477 .withRestrict(),
4478 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004479 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004480 PrivateVarsPos[VD] = Counter;
4481 ++Counter;
4482 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004483 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004484 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004485 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004486 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004487 std::string Name =
4488 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004489 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004490 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4491 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004492 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004493 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004494 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004495 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004496 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004497 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004498 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004499 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004500
4501 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004502 LValue Base = CGF.EmitLoadOfPointerLValue(
4503 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4504 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004505 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004506 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004507 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4508 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4509 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4510 LValue RefLVal =
4511 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4512 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004513 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004514 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004515 ++Counter;
4516 }
4517 CGF.FinishFunction();
4518 return TaskPrivatesMap;
4519}
4520
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004521static bool stable_sort_comparator(const PrivateDataTy P1,
4522 const PrivateDataTy P2) {
4523 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004524}
4525
Alexey Bataevf93095a2016-05-05 08:46:22 +00004526/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004527static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004528 const OMPExecutableDirective &D,
4529 Address KmpTaskSharedsPtr, LValue TDBase,
4530 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4531 QualType SharedsTy, QualType SharedsPtrTy,
4532 const OMPTaskDataTy &Data,
4533 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004534 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004535 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4536 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004537 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4538 ? OMPD_taskloop
4539 : OMPD_task;
4540 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4541 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004542 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004543 bool IsTargetTask =
4544 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4545 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4546 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4547 // PointersArray and SizesArray. The original variables for these arrays are
4548 // not captured and we get their addresses explicitly.
4549 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004550 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004551 SrcBase = CGF.MakeAddrLValue(
4552 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4553 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4554 SharedsTy);
4555 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004556 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004557 for (const PrivateDataTy &Pair : Privates) {
4558 const VarDecl *VD = Pair.second.PrivateCopy;
4559 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004560 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4561 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004562 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004563 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4564 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004565 // Check if the variable is the target-based BasePointersArray,
4566 // PointersArray or SizesArray.
4567 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004568 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004569 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004570 if (IsTargetTask && !SharedField) {
4571 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4572 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4573 cast<CapturedDecl>(OriginalVD->getDeclContext())
4574 ->getNumParams() == 0 &&
4575 isa<TranslationUnitDecl>(
4576 cast<CapturedDecl>(OriginalVD->getDeclContext())
4577 ->getDeclContext()) &&
4578 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004579 SharedRefLValue =
4580 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4581 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004582 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4583 SharedRefLValue = CGF.MakeAddrLValue(
4584 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4585 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4586 SharedRefLValue.getTBAAInfo());
4587 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004588 if (Type->isArrayType()) {
4589 // Initialize firstprivate array.
4590 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4591 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004592 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004593 } else {
4594 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004595 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004596 CGF.EmitOMPAggregateAssign(
4597 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4598 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4599 Address SrcElement) {
4600 // Clean up any temporaries needed by the initialization.
4601 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4602 InitScope.addPrivate(
4603 Elem, [SrcElement]() -> Address { return SrcElement; });
4604 (void)InitScope.Privatize();
4605 // Emit initialization for single element.
4606 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4607 CGF, &CapturesInfo);
4608 CGF.EmitAnyExprToMem(Init, DestElement,
4609 Init->getType().getQualifiers(),
4610 /*IsInitializer=*/false);
4611 });
4612 }
4613 } else {
4614 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4615 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4616 return SharedRefLValue.getAddress();
4617 });
4618 (void)InitScope.Privatize();
4619 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4620 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4621 /*capturedByInit=*/false);
4622 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004623 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004624 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004625 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004626 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004627 ++FI;
4628 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004629}
4630
4631/// Check if duplication function is required for taskloops.
4632static bool checkInitIsRequired(CodeGenFunction &CGF,
4633 ArrayRef<PrivateDataTy> Privates) {
4634 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004635 for (const PrivateDataTy &Pair : Privates) {
4636 const VarDecl *VD = Pair.second.PrivateCopy;
4637 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004638 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4639 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004640 if (InitRequired)
4641 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004642 }
4643 return InitRequired;
4644}
4645
4646
4647/// Emit task_dup function (for initialization of
4648/// private/firstprivate/lastprivate vars and last_iter flag)
4649/// \code
4650/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4651/// lastpriv) {
4652/// // setup lastprivate flag
4653/// task_dst->last = lastpriv;
4654/// // could be constructor calls here...
4655/// }
4656/// \endcode
4657static llvm::Value *
4658emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4659 const OMPExecutableDirective &D,
4660 QualType KmpTaskTWithPrivatesPtrQTy,
4661 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4662 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4663 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4664 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004665 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004666 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004667 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4668 KmpTaskTWithPrivatesPtrQTy,
4669 ImplicitParamDecl::Other);
4670 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4671 KmpTaskTWithPrivatesPtrQTy,
4672 ImplicitParamDecl::Other);
4673 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4674 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004675 Args.push_back(&DstArg);
4676 Args.push_back(&SrcArg);
4677 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004678 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004679 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004680 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004681 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4682 auto *TaskDup = llvm::Function::Create(
4683 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004684 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004685 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004686 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004687 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4688 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004689
4690 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4691 CGF.GetAddrOfLocalVar(&DstArg),
4692 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4693 // task_dst->liter = lastpriv;
4694 if (WithLastIter) {
4695 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4696 LValue Base = CGF.EmitLValueForField(
4697 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4698 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4699 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4700 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4701 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4702 }
4703
4704 // Emit initial values for private copies (if any).
4705 assert(!Privates.empty());
4706 Address KmpTaskSharedsPtr = Address::invalid();
4707 if (!Data.FirstprivateVars.empty()) {
4708 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4709 CGF.GetAddrOfLocalVar(&SrcArg),
4710 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4711 LValue Base = CGF.EmitLValueForField(
4712 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4713 KmpTaskSharedsPtr = Address(
4714 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4715 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4716 KmpTaskTShareds)),
4717 Loc),
4718 CGF.getNaturalTypeAlignment(SharedsTy));
4719 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004720 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4721 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004722 CGF.FinishFunction();
4723 return TaskDup;
4724}
4725
Alexey Bataev8a831592016-05-10 10:36:51 +00004726/// Checks if destructor function is required to be generated.
4727/// \return true if cleanups are required, false otherwise.
4728static bool
4729checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4730 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004731 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4732 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4733 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004734 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4735 if (NeedsCleanup)
4736 break;
4737 }
4738 return NeedsCleanup;
4739}
4740
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004741CGOpenMPRuntime::TaskResultTy
4742CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4743 const OMPExecutableDirective &D,
4744 llvm::Value *TaskFunction, QualType SharedsTy,
4745 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004746 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004747 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004748 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004749 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004750 for (const Expr *E : Data.PrivateVars) {
4751 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004752 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004753 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004754 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004755 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004756 ++I;
4757 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004758 I = Data.FirstprivateCopies.begin();
4759 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004760 for (const Expr *E : Data.FirstprivateVars) {
4761 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004762 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004763 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004764 PrivateHelpersTy(
4765 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004766 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004767 ++I;
4768 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004769 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004770 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004771 for (const Expr *E : Data.LastprivateVars) {
4772 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004773 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004774 C.getDeclAlign(VD),
4775 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004776 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004777 ++I;
4778 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004779 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004780 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004781 // Build type kmp_routine_entry_t (if not built yet).
4782 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004783 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004784 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4785 if (SavedKmpTaskloopTQTy.isNull()) {
4786 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4787 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4788 }
4789 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004790 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004791 assert((D.getDirectiveKind() == OMPD_task ||
4792 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4793 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4794 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004795 if (SavedKmpTaskTQTy.isNull()) {
4796 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4797 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4798 }
4799 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004800 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004801 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004802 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004803 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004804 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004805 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004806 QualType KmpTaskTWithPrivatesPtrQTy =
4807 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004808 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4809 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4810 KmpTaskTWithPrivatesTy->getPointerTo();
4811 llvm::Value *KmpTaskTWithPrivatesTySize =
4812 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004813 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4814
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004815 // Emit initial values for private copies (if any).
4816 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004817 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004818 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004819 if (!Privates.empty()) {
4820 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004821 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4822 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4823 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004824 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4825 TaskPrivatesMap, TaskPrivatesMapTy);
4826 } else {
4827 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4828 cast<llvm::PointerType>(TaskPrivatesMapTy));
4829 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004830 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4831 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004832 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004833 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4834 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4835 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004836
4837 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4838 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4839 // kmp_routine_entry_t *task_entry);
4840 // Task flags. Format is taken from
4841 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4842 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004843 enum {
4844 TiedFlag = 0x1,
4845 FinalFlag = 0x2,
4846 DestructorsFlag = 0x8,
4847 PriorityFlag = 0x20
4848 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004849 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004850 bool NeedsCleanup = false;
4851 if (!Privates.empty()) {
4852 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4853 if (NeedsCleanup)
4854 Flags = Flags | DestructorsFlag;
4855 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004856 if (Data.Priority.getInt())
4857 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004858 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004859 Data.Final.getPointer()
4860 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004861 CGF.Builder.getInt32(FinalFlag),
4862 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004863 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004864 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004865 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004866 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4867 getThreadID(CGF, Loc), TaskFlags,
4868 KmpTaskTWithPrivatesTySize, SharedsSize,
4869 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4870 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004871 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004872 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004873 llvm::Value *NewTaskNewTaskTTy =
4874 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4875 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004876 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4877 KmpTaskTWithPrivatesQTy);
4878 LValue TDBase =
4879 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004880 // Fill the data in the resulting kmp_task_t record.
4881 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004882 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004883 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004884 KmpTaskSharedsPtr =
4885 Address(CGF.EmitLoadOfScalar(
4886 CGF.EmitLValueForField(
4887 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4888 KmpTaskTShareds)),
4889 Loc),
4890 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004891 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4892 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004893 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004894 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004895 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004896 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004897 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004898 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4899 SharedsTy, SharedsPtrTy, Data, Privates,
4900 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004901 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4902 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4903 Result.TaskDupFn = emitTaskDupFunction(
4904 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4905 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4906 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004907 }
4908 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004909 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4910 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004911 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004912 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004913 const RecordDecl *KmpCmplrdataUD =
4914 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004915 if (NeedsCleanup) {
4916 llvm::Value *DestructorFn = emitDestructorsFunction(
4917 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4918 KmpTaskTWithPrivatesQTy);
4919 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4920 LValue DestructorsLV = CGF.EmitLValueForField(
4921 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4922 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4923 DestructorFn, KmpRoutineEntryPtrTy),
4924 DestructorsLV);
4925 }
4926 // Set priority.
4927 if (Data.Priority.getInt()) {
4928 LValue Data2LV = CGF.EmitLValueForField(
4929 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4930 LValue PriorityLV = CGF.EmitLValueForField(
4931 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4932 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4933 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004934 Result.NewTask = NewTask;
4935 Result.TaskEntry = TaskEntry;
4936 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4937 Result.TDBase = TDBase;
4938 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4939 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004940}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004941
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004942void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4943 const OMPExecutableDirective &D,
4944 llvm::Value *TaskFunction,
4945 QualType SharedsTy, Address Shareds,
4946 const Expr *IfCond,
4947 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004948 if (!CGF.HaveInsertPoint())
4949 return;
4950
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004951 TaskResultTy Result =
4952 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4953 llvm::Value *NewTask = Result.NewTask;
4954 llvm::Value *TaskEntry = Result.TaskEntry;
4955 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4956 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004957 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4958 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004959 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004960 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004961 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004962 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004963 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004964 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004965 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4966 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004967 QualType FlagsTy =
4968 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004969 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4970 if (KmpDependInfoTy.isNull()) {
4971 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4972 KmpDependInfoRD->startDefinition();
4973 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4974 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4975 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4976 KmpDependInfoRD->completeDefinition();
4977 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004978 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004979 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004980 }
John McCall7f416cc2015-09-08 08:05:57 +00004981 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004982 // Define type kmp_depend_info[<Dependences.size()>];
4983 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004984 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004985 ArrayType::Normal, /*IndexTypeQuals=*/0);
4986 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004987 DependenciesArray =
4988 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004989 for (unsigned I = 0; I < NumDependencies; ++I) {
4990 const Expr *E = Data.Dependences[I].second;
4991 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004992 llvm::Value *Size;
4993 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004994 if (const auto *ASE =
4995 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004996 LValue UpAddrLVal =
4997 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4998 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004999 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005000 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005001 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005002 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5003 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005004 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005005 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005006 }
5007 LValue Base = CGF.MakeAddrLValue(
5008 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005009 KmpDependInfoTy);
5010 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005011 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005012 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005013 CGF.EmitStoreOfScalar(
5014 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5015 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005016 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005017 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005018 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5019 CGF.EmitStoreOfScalar(Size, LenLVal);
5020 // deps[i].flags = <Dependences[i].first>;
5021 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005022 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005023 case OMPC_DEPEND_in:
5024 DepKind = DepIn;
5025 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005026 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005027 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005028 case OMPC_DEPEND_inout:
5029 DepKind = DepInOut;
5030 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005031 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005032 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005033 case OMPC_DEPEND_unknown:
5034 llvm_unreachable("Unknown task dependence type");
5035 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005036 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005037 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5038 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5039 FlagsLVal);
5040 }
John McCall7f416cc2015-09-08 08:05:57 +00005041 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5042 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005043 CGF.VoidPtrTy);
5044 }
5045
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005046 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005047 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005048 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5049 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5050 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5051 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005052 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5053 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005054 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5055 llvm::Value *DepTaskArgs[7];
5056 if (NumDependencies) {
5057 DepTaskArgs[0] = UpLoc;
5058 DepTaskArgs[1] = ThreadID;
5059 DepTaskArgs[2] = NewTask;
5060 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5061 DepTaskArgs[4] = DependenciesArray.getPointer();
5062 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5063 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5064 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005065 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5066 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005067 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005068 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005069 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005070 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005071 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5072 }
John McCall7f416cc2015-09-08 08:05:57 +00005073 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005074 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005075 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005076 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005077 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005078 TaskArgs);
5079 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005080 // Check if parent region is untied and build return for untied task;
5081 if (auto *Region =
5082 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5083 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005084 };
John McCall7f416cc2015-09-08 08:05:57 +00005085
5086 llvm::Value *DepWaitTaskArgs[6];
5087 if (NumDependencies) {
5088 DepWaitTaskArgs[0] = UpLoc;
5089 DepWaitTaskArgs[1] = ThreadID;
5090 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5091 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5092 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5093 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5094 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005095 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005096 NumDependencies, &DepWaitTaskArgs,
5097 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005098 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005099 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5100 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5101 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5102 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5103 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005104 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005105 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005106 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005107 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005108 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5109 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005110 Action.Enter(CGF);
5111 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005112 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005113 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005114 };
5115
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005116 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5117 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005118 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5119 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005120 RegionCodeGenTy RCG(CodeGen);
5121 CommonActionTy Action(
5122 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5123 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5124 RCG.setAction(Action);
5125 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005126 };
John McCall7f416cc2015-09-08 08:05:57 +00005127
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005128 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005129 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005130 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005131 RegionCodeGenTy ThenRCG(ThenCodeGen);
5132 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005133 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005134}
5135
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005136void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5137 const OMPLoopDirective &D,
5138 llvm::Value *TaskFunction,
5139 QualType SharedsTy, Address Shareds,
5140 const Expr *IfCond,
5141 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005142 if (!CGF.HaveInsertPoint())
5143 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005144 TaskResultTy Result =
5145 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005146 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005147 // libcall.
5148 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5149 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5150 // sched, kmp_uint64 grainsize, void *task_dup);
5151 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5152 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5153 llvm::Value *IfVal;
5154 if (IfCond) {
5155 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5156 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005157 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005158 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005159 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005160
5161 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005162 Result.TDBase,
5163 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005164 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005165 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5166 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5167 /*IsInitializer=*/true);
5168 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005169 Result.TDBase,
5170 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005171 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005172 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5173 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5174 /*IsInitializer=*/true);
5175 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005176 Result.TDBase,
5177 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005178 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005179 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5180 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5181 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005182 // Store reductions address.
5183 LValue RedLVal = CGF.EmitLValueForField(
5184 Result.TDBase,
5185 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005186 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005187 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005188 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005189 CGF.EmitNullInitialization(RedLVal.getAddress(),
5190 CGF.getContext().VoidPtrTy);
5191 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005192 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005193 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005194 UpLoc,
5195 ThreadID,
5196 Result.NewTask,
5197 IfVal,
5198 LBLVal.getPointer(),
5199 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005200 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005201 llvm::ConstantInt::getNullValue(
5202 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005203 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005204 CGF.IntTy, Data.Schedule.getPointer()
5205 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005206 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005207 Data.Schedule.getPointer()
5208 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005209 /*isSigned=*/false)
5210 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005211 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5212 Result.TaskDupFn, CGF.VoidPtrTy)
5213 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005214 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5215}
5216
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005217/// \brief Emit reduction operation for each element of array (required for
5218/// array sections) LHS op = RHS.
5219/// \param Type Type of array.
5220/// \param LHSVar Variable on the left side of the reduction operation
5221/// (references element of array in original variable).
5222/// \param RHSVar Variable on the right side of the reduction operation
5223/// (references element of array in original variable).
5224/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5225/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005226static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005227 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5228 const VarDecl *RHSVar,
5229 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5230 const Expr *, const Expr *)> &RedOpGen,
5231 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5232 const Expr *UpExpr = nullptr) {
5233 // Perform element-by-element initialization.
5234 QualType ElementTy;
5235 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5236 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5237
5238 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005239 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5240 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005241
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005242 llvm::Value *RHSBegin = RHSAddr.getPointer();
5243 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005244 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005245 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005246 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005247 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5248 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5249 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005250 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5251 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5252
5253 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005254 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005255 CGF.EmitBlock(BodyBB);
5256
5257 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5258
5259 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5260 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5261 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5262 Address RHSElementCurrent =
5263 Address(RHSElementPHI,
5264 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5265
5266 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5267 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5268 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5269 Address LHSElementCurrent =
5270 Address(LHSElementPHI,
5271 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5272
5273 // Emit copy.
5274 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005275 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5276 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005277 Scope.Privatize();
5278 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5279 Scope.ForceCleanup();
5280
5281 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005282 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005283 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005284 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005285 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5286 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005287 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005288 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5289 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5290 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5291 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5292
5293 // Done.
5294 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5295}
5296
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005297/// Emit reduction combiner. If the combiner is a simple expression emit it as
5298/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5299/// UDR combiner function.
5300static void emitReductionCombiner(CodeGenFunction &CGF,
5301 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005302 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5303 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5304 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005305 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005306 if (const auto *DRD =
5307 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005308 std::pair<llvm::Function *, llvm::Function *> Reduction =
5309 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5310 RValue Func = RValue::get(Reduction.first);
5311 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5312 CGF.EmitIgnoredExpr(ReductionOp);
5313 return;
5314 }
5315 CGF.EmitIgnoredExpr(ReductionOp);
5316}
5317
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005318llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005319 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5320 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5321 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005322 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005323
5324 // void reduction_func(void *LHSArg, void *RHSArg);
5325 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005326 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5327 ImplicitParamDecl::Other);
5328 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5329 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005330 Args.push_back(&LHSArg);
5331 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005332 const auto &CGFI =
5333 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005334 std::string Name = getName({"omp", "reduction", "reduction_func"});
5335 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5336 llvm::GlobalValue::InternalLinkage, Name,
5337 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005338 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005339 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005340 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005341 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005342
5343 // Dst = (void*[n])(LHSArg);
5344 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005345 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5346 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5347 ArgsType), CGF.getPointerAlign());
5348 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5349 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5350 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005351
5352 // ...
5353 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5354 // ...
5355 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005356 auto IPriv = Privates.begin();
5357 unsigned Idx = 0;
5358 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005359 const auto *RHSVar =
5360 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5361 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005362 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005363 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005364 const auto *LHSVar =
5365 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5366 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005367 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005368 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005369 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005370 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005371 // Get array size and emit VLA type.
5372 ++Idx;
5373 Address Elem =
5374 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5375 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005376 const VariableArrayType *VLA =
5377 CGF.getContext().getAsVariableArrayType(PrivTy);
5378 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005379 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005380 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005381 CGF.EmitVariablyModifiedType(PrivTy);
5382 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005383 }
5384 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005385 IPriv = Privates.begin();
5386 auto ILHS = LHSExprs.begin();
5387 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005388 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005389 if ((*IPriv)->getType()->isArrayType()) {
5390 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005391 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5392 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005393 EmitOMPAggregateReduction(
5394 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5395 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5396 emitReductionCombiner(CGF, E);
5397 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005398 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005399 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005400 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005401 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005402 ++IPriv;
5403 ++ILHS;
5404 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005405 }
5406 Scope.ForceCleanup();
5407 CGF.FinishFunction();
5408 return Fn;
5409}
5410
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005411void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5412 const Expr *ReductionOp,
5413 const Expr *PrivateRef,
5414 const DeclRefExpr *LHS,
5415 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005416 if (PrivateRef->getType()->isArrayType()) {
5417 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005418 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5419 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005420 EmitOMPAggregateReduction(
5421 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5422 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5423 emitReductionCombiner(CGF, ReductionOp);
5424 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005425 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005426 // Emit reduction for array subscript or single variable.
5427 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005428 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005429}
5430
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005431void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005432 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005433 ArrayRef<const Expr *> LHSExprs,
5434 ArrayRef<const Expr *> RHSExprs,
5435 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005436 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005437 if (!CGF.HaveInsertPoint())
5438 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005439
5440 bool WithNowait = Options.WithNowait;
5441 bool SimpleReduction = Options.SimpleReduction;
5442
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005443 // Next code should be emitted for reduction:
5444 //
5445 // static kmp_critical_name lock = { 0 };
5446 //
5447 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5448 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5449 // ...
5450 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5451 // *(Type<n>-1*)rhs[<n>-1]);
5452 // }
5453 //
5454 // ...
5455 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5456 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5457 // RedList, reduce_func, &<lock>)) {
5458 // case 1:
5459 // ...
5460 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5461 // ...
5462 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5463 // break;
5464 // case 2:
5465 // ...
5466 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5467 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005468 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005469 // break;
5470 // default:;
5471 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005472 //
5473 // if SimpleReduction is true, only the next code is generated:
5474 // ...
5475 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5476 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005477
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005478 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005479
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005480 if (SimpleReduction) {
5481 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005482 auto IPriv = Privates.begin();
5483 auto ILHS = LHSExprs.begin();
5484 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005485 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005486 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5487 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005488 ++IPriv;
5489 ++ILHS;
5490 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005491 }
5492 return;
5493 }
5494
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005495 // 1. Build a list of reduction variables.
5496 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005497 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005498 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005499 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005500 // Reserve place for array size.
5501 ++Size;
5502 }
5503 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005504 QualType ReductionArrayTy =
5505 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5506 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005507 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005508 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005509 auto IPriv = Privates.begin();
5510 unsigned Idx = 0;
5511 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005512 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005513 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005514 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005515 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005516 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5517 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005518 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005519 // Store array size.
5520 ++Idx;
5521 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5522 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005523 llvm::Value *Size = CGF.Builder.CreateIntCast(
5524 CGF.getVLASize(
5525 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005526 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005527 CGF.SizeTy, /*isSigned=*/false);
5528 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5529 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005530 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005531 }
5532
5533 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005534 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005535 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5536 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005537
5538 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005539 std::string Name = getName({"reduction"});
5540 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005541
5542 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5543 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005544 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5545 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5546 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5547 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005548 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005549 llvm::Value *Args[] = {
5550 IdentTLoc, // ident_t *<loc>
5551 ThreadId, // i32 <gtid>
5552 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5553 ReductionArrayTySize, // size_type sizeof(RedList)
5554 RL, // void *RedList
5555 ReductionFn, // void (*) (void *, void *) <reduce_func>
5556 Lock // kmp_critical_name *&<lock>
5557 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005558 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005559 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5560 : OMPRTL__kmpc_reduce),
5561 Args);
5562
5563 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005564 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5565 llvm::SwitchInst *SwInst =
5566 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005567
5568 // 6. Build case 1:
5569 // ...
5570 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5571 // ...
5572 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5573 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005574 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005575 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5576 CGF.EmitBlock(Case1BB);
5577
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005578 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5579 llvm::Value *EndArgs[] = {
5580 IdentTLoc, // ident_t *<loc>
5581 ThreadId, // i32 <gtid>
5582 Lock // kmp_critical_name *&<lock>
5583 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005584 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5585 CodeGenFunction &CGF, PrePostActionTy &Action) {
5586 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005587 auto IPriv = Privates.begin();
5588 auto ILHS = LHSExprs.begin();
5589 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005590 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005591 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5592 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005593 ++IPriv;
5594 ++ILHS;
5595 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005596 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005597 };
5598 RegionCodeGenTy RCG(CodeGen);
5599 CommonActionTy Action(
5600 nullptr, llvm::None,
5601 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5602 : OMPRTL__kmpc_end_reduce),
5603 EndArgs);
5604 RCG.setAction(Action);
5605 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005606
5607 CGF.EmitBranch(DefaultBB);
5608
5609 // 7. Build case 2:
5610 // ...
5611 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5612 // ...
5613 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005614 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005615 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5616 CGF.EmitBlock(Case2BB);
5617
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005618 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5619 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005620 auto ILHS = LHSExprs.begin();
5621 auto IRHS = RHSExprs.begin();
5622 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005623 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005624 const Expr *XExpr = nullptr;
5625 const Expr *EExpr = nullptr;
5626 const Expr *UpExpr = nullptr;
5627 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005628 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005629 if (BO->getOpcode() == BO_Assign) {
5630 XExpr = BO->getLHS();
5631 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005632 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005633 }
5634 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005635 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005636 if (RHSExpr) {
5637 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005638 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005639 RHSExpr->IgnoreParenImpCasts())) {
5640 // If this is a conditional operator, analyze its condition for
5641 // min/max reduction operator.
5642 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005643 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005644 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005645 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5646 EExpr = BORHS->getRHS();
5647 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005648 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005649 }
5650 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005651 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005652 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005653 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5654 const Expr *EExpr, const Expr *UpExpr) {
5655 LValue X = CGF.EmitLValue(XExpr);
5656 RValue E;
5657 if (EExpr)
5658 E = CGF.EmitAnyExpr(EExpr);
5659 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005660 X, E, BO, /*IsXLHSInRHSPart=*/true,
5661 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005662 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005663 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5664 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005665 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005666 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5667 CGF.emitOMPSimpleStore(
5668 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5669 VD->getType().getNonReferenceType(), Loc);
5670 return LHSTemp;
5671 });
5672 (void)PrivateScope.Privatize();
5673 return CGF.EmitAnyExpr(UpExpr);
5674 });
5675 };
5676 if ((*IPriv)->getType()->isArrayType()) {
5677 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005678 const auto *RHSVar =
5679 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005680 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5681 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005682 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005683 // Emit atomic reduction for array subscript or single variable.
5684 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005685 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005686 } else {
5687 // Emit as a critical region.
5688 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005689 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005690 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005691 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005692 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005693 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005694 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5695 Action.Enter(CGF);
5696 emitReductionCombiner(CGF, E);
5697 },
5698 Loc);
5699 };
5700 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005701 const auto *LHSVar =
5702 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5703 const auto *RHSVar =
5704 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005705 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5706 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005707 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005708 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005709 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005710 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005711 ++ILHS;
5712 ++IRHS;
5713 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005714 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005715 };
5716 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5717 if (!WithNowait) {
5718 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5719 llvm::Value *EndArgs[] = {
5720 IdentTLoc, // ident_t *<loc>
5721 ThreadId, // i32 <gtid>
5722 Lock // kmp_critical_name *&<lock>
5723 };
5724 CommonActionTy Action(nullptr, llvm::None,
5725 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5726 EndArgs);
5727 AtomicRCG.setAction(Action);
5728 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005729 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005730 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005731 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005732
5733 CGF.EmitBranch(DefaultBB);
5734 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5735}
5736
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005737/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005738/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5739static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5740 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005741 SmallString<256> Buffer;
5742 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005743 const clang::DeclRefExpr *DE;
5744 const VarDecl *D = ::getBaseDecl(Ref, DE);
5745 if (!D)
5746 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5747 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005748 std::string Name = CGM.getOpenMPRuntime().getName(
5749 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5750 Out << Prefix << Name << "_"
5751 << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005752 return Out.str();
5753}
5754
5755/// Emits reduction initializer function:
5756/// \code
5757/// void @.red_init(void* %arg) {
5758/// %0 = bitcast void* %arg to <type>*
5759/// store <type> <init>, <type>* %0
5760/// ret void
5761/// }
5762/// \endcode
5763static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5764 SourceLocation Loc,
5765 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005766 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005767 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005768 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5769 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005770 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005771 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005772 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005773 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005774 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005775 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005776 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005777 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005778 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005779 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005780 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005781 Address PrivateAddr = CGF.EmitLoadOfPointer(
5782 CGF.GetAddrOfLocalVar(&Param),
5783 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5784 llvm::Value *Size = nullptr;
5785 // If the size of the reduction item is non-constant, load it from global
5786 // threadprivate variable.
5787 if (RCG.getSizes(N).second) {
5788 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5789 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005790 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005791 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5792 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005793 }
5794 RCG.emitAggregateType(CGF, N, Size);
5795 LValue SharedLVal;
5796 // If initializer uses initializer from declare reduction construct, emit a
5797 // pointer to the address of the original reduction item (reuired by reduction
5798 // initializer)
5799 if (RCG.usesReductionInitializer(N)) {
5800 Address SharedAddr =
5801 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5802 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005803 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005804 SharedAddr = CGF.EmitLoadOfPointer(
5805 SharedAddr,
5806 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005807 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5808 } else {
5809 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5810 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5811 CGM.getContext().VoidPtrTy);
5812 }
5813 // Emit the initializer:
5814 // %0 = bitcast void* %arg to <type>*
5815 // store <type> <init>, <type>* %0
5816 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5817 [](CodeGenFunction &) { return false; });
5818 CGF.FinishFunction();
5819 return Fn;
5820}
5821
5822/// Emits reduction combiner function:
5823/// \code
5824/// void @.red_comb(void* %arg0, void* %arg1) {
5825/// %lhs = bitcast void* %arg0 to <type>*
5826/// %rhs = bitcast void* %arg1 to <type>*
5827/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5828/// store <type> %2, <type>* %lhs
5829/// ret void
5830/// }
5831/// \endcode
5832static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5833 SourceLocation Loc,
5834 ReductionCodeGen &RCG, unsigned N,
5835 const Expr *ReductionOp,
5836 const Expr *LHS, const Expr *RHS,
5837 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005838 ASTContext &C = CGM.getContext();
5839 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5840 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005841 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005842 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5843 C.VoidPtrTy, ImplicitParamDecl::Other);
5844 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5845 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005846 Args.emplace_back(&ParamInOut);
5847 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005848 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005849 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005850 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005851 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005852 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005853 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005854 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005855 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005856 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005857 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005858 llvm::Value *Size = nullptr;
5859 // If the size of the reduction item is non-constant, load it from global
5860 // threadprivate variable.
5861 if (RCG.getSizes(N).second) {
5862 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5863 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005864 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005865 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5866 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005867 }
5868 RCG.emitAggregateType(CGF, N, Size);
5869 // Remap lhs and rhs variables to the addresses of the function arguments.
5870 // %lhs = bitcast void* %arg0 to <type>*
5871 // %rhs = bitcast void* %arg1 to <type>*
5872 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005873 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005874 // Pull out the pointer to the variable.
5875 Address PtrAddr = CGF.EmitLoadOfPointer(
5876 CGF.GetAddrOfLocalVar(&ParamInOut),
5877 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5878 return CGF.Builder.CreateElementBitCast(
5879 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5880 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005881 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005882 // Pull out the pointer to the variable.
5883 Address PtrAddr = CGF.EmitLoadOfPointer(
5884 CGF.GetAddrOfLocalVar(&ParamIn),
5885 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5886 return CGF.Builder.CreateElementBitCast(
5887 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5888 });
5889 PrivateScope.Privatize();
5890 // Emit the combiner body:
5891 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5892 // store <type> %2, <type>* %lhs
5893 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5894 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5895 cast<DeclRefExpr>(RHS));
5896 CGF.FinishFunction();
5897 return Fn;
5898}
5899
5900/// Emits reduction finalizer function:
5901/// \code
5902/// void @.red_fini(void* %arg) {
5903/// %0 = bitcast void* %arg to <type>*
5904/// <destroy>(<type>* %0)
5905/// ret void
5906/// }
5907/// \endcode
5908static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5909 SourceLocation Loc,
5910 ReductionCodeGen &RCG, unsigned N) {
5911 if (!RCG.needCleanups(N))
5912 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005913 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005914 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005915 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5916 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005917 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005918 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005919 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005920 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005921 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005922 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005923 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005924 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005925 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005926 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005927 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005928 Address PrivateAddr = CGF.EmitLoadOfPointer(
5929 CGF.GetAddrOfLocalVar(&Param),
5930 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5931 llvm::Value *Size = nullptr;
5932 // If the size of the reduction item is non-constant, load it from global
5933 // threadprivate variable.
5934 if (RCG.getSizes(N).second) {
5935 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5936 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005937 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005938 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5939 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005940 }
5941 RCG.emitAggregateType(CGF, N, Size);
5942 // Emit the finalizer body:
5943 // <destroy>(<type>* %0)
5944 RCG.emitCleanups(CGF, N, PrivateAddr);
5945 CGF.FinishFunction();
5946 return Fn;
5947}
5948
5949llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5950 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5951 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5952 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5953 return nullptr;
5954
5955 // Build typedef struct:
5956 // kmp_task_red_input {
5957 // void *reduce_shar; // shared reduction item
5958 // size_t reduce_size; // size of data item
5959 // void *reduce_init; // data initialization routine
5960 // void *reduce_fini; // data finalization routine
5961 // void *reduce_comb; // data combiner routine
5962 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5963 // } kmp_task_red_input_t;
5964 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005965 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005966 RD->startDefinition();
5967 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5968 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5969 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5970 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5971 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5972 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5973 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5974 RD->completeDefinition();
5975 QualType RDType = C.getRecordType(RD);
5976 unsigned Size = Data.ReductionVars.size();
5977 llvm::APInt ArraySize(/*numBits=*/64, Size);
5978 QualType ArrayRDType = C.getConstantArrayType(
5979 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5980 // kmp_task_red_input_t .rd_input.[Size];
5981 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5982 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5983 Data.ReductionOps);
5984 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5985 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5986 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5987 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5988 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5989 TaskRedInput.getPointer(), Idxs,
5990 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5991 ".rd_input.gep.");
5992 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5993 // ElemLVal.reduce_shar = &Shareds[Cnt];
5994 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5995 RCG.emitSharedLValue(CGF, Cnt);
5996 llvm::Value *CastedShared =
5997 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5998 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5999 RCG.emitAggregateType(CGF, Cnt);
6000 llvm::Value *SizeValInChars;
6001 llvm::Value *SizeVal;
6002 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6003 // We use delayed creation/initialization for VLAs, array sections and
6004 // custom reduction initializations. It is required because runtime does not
6005 // provide the way to pass the sizes of VLAs/array sections to
6006 // initializer/combiner/finalizer functions and does not pass the pointer to
6007 // original reduction item to the initializer. Instead threadprivate global
6008 // variables are used to store these values and use them in the functions.
6009 bool DelayedCreation = !!SizeVal;
6010 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6011 /*isSigned=*/false);
6012 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6013 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6014 // ElemLVal.reduce_init = init;
6015 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6016 llvm::Value *InitAddr =
6017 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6018 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6019 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6020 // ElemLVal.reduce_fini = fini;
6021 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6022 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6023 llvm::Value *FiniAddr = Fini
6024 ? CGF.EmitCastToVoidPtr(Fini)
6025 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6026 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6027 // ElemLVal.reduce_comb = comb;
6028 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6029 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6030 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6031 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6032 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6033 // ElemLVal.flags = 0;
6034 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6035 if (DelayedCreation) {
6036 CGF.EmitStoreOfScalar(
6037 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6038 FlagsLVal);
6039 } else
6040 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6041 }
6042 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6043 // *data);
6044 llvm::Value *Args[] = {
6045 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6046 /*isSigned=*/true),
6047 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6048 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6049 CGM.VoidPtrTy)};
6050 return CGF.EmitRuntimeCall(
6051 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6052}
6053
6054void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6055 SourceLocation Loc,
6056 ReductionCodeGen &RCG,
6057 unsigned N) {
6058 auto Sizes = RCG.getSizes(N);
6059 // Emit threadprivate global variable if the type is non-constant
6060 // (Sizes.second = nullptr).
6061 if (Sizes.second) {
6062 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6063 /*isSigned=*/false);
6064 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6065 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006066 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006067 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6068 }
6069 // Store address of the original reduction item if custom initializer is used.
6070 if (RCG.usesReductionInitializer(N)) {
6071 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6072 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006073 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006074 CGF.Builder.CreateStore(
6075 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6076 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6077 SharedAddr, /*IsVolatile=*/false);
6078 }
6079}
6080
6081Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6082 SourceLocation Loc,
6083 llvm::Value *ReductionsPtr,
6084 LValue SharedLVal) {
6085 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6086 // *d);
6087 llvm::Value *Args[] = {
6088 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6089 /*isSigned=*/true),
6090 ReductionsPtr,
6091 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6092 CGM.VoidPtrTy)};
6093 return Address(
6094 CGF.EmitRuntimeCall(
6095 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6096 SharedLVal.getAlignment());
6097}
6098
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006099void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6100 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006101 if (!CGF.HaveInsertPoint())
6102 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006103 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6104 // global_tid);
6105 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6106 // Ignore return result until untied tasks are supported.
6107 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006108 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6109 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006110}
6111
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006112void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006113 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006114 const RegionCodeGenTy &CodeGen,
6115 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006116 if (!CGF.HaveInsertPoint())
6117 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006118 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006119 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006120}
6121
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006122namespace {
6123enum RTCancelKind {
6124 CancelNoreq = 0,
6125 CancelParallel = 1,
6126 CancelLoop = 2,
6127 CancelSections = 3,
6128 CancelTaskgroup = 4
6129};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006130} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006131
6132static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6133 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006134 if (CancelRegion == OMPD_parallel)
6135 CancelKind = CancelParallel;
6136 else if (CancelRegion == OMPD_for)
6137 CancelKind = CancelLoop;
6138 else if (CancelRegion == OMPD_sections)
6139 CancelKind = CancelSections;
6140 else {
6141 assert(CancelRegion == OMPD_taskgroup);
6142 CancelKind = CancelTaskgroup;
6143 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006144 return CancelKind;
6145}
6146
6147void CGOpenMPRuntime::emitCancellationPointCall(
6148 CodeGenFunction &CGF, SourceLocation Loc,
6149 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006150 if (!CGF.HaveInsertPoint())
6151 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006152 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6153 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006154 if (auto *OMPRegionInfo =
6155 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006156 // For 'cancellation point taskgroup', the task region info may not have a
6157 // cancel. This may instead happen in another adjacent task.
6158 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006159 llvm::Value *Args[] = {
6160 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6161 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006162 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006163 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006164 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6165 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006166 // exit from construct;
6167 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006168 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6169 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6170 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006171 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6172 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006173 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006174 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006175 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006176 CGF.EmitBranchThroughCleanup(CancelDest);
6177 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6178 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006179 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006180}
6181
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006182void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006183 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006184 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006185 if (!CGF.HaveInsertPoint())
6186 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006187 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6188 // kmp_int32 cncl_kind);
6189 if (auto *OMPRegionInfo =
6190 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006191 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6192 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006193 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006194 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006195 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006196 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6197 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006198 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006199 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006200 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006201 // exit from construct;
6202 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006203 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6204 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6205 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006206 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6207 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006208 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006209 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006210 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6211 CGF.EmitBranchThroughCleanup(CancelDest);
6212 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6213 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006214 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006215 emitOMPIfClause(CGF, IfCond, ThenGen,
6216 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006217 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006218 RegionCodeGenTy ThenRCG(ThenGen);
6219 ThenRCG(CGF);
6220 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006221 }
6222}
Samuel Antaobed3c462015-10-02 16:14:20 +00006223
Samuel Antaoee8fb302016-01-06 13:42:12 +00006224void CGOpenMPRuntime::emitTargetOutlinedFunction(
6225 const OMPExecutableDirective &D, StringRef ParentName,
6226 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006227 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006228 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006229 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6230 IsOffloadEntry, CodeGen);
6231}
6232
6233void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6234 const OMPExecutableDirective &D, StringRef ParentName,
6235 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6236 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006237 // Create a unique name for the entry function using the source location
6238 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006239 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006240 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006241 //
6242 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006243 // mangled name of the function that encloses the target region and BB is the
6244 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006245
6246 unsigned DeviceID;
6247 unsigned FileID;
6248 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006249 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006250 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006251 SmallString<64> EntryFnName;
6252 {
6253 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006254 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6255 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006256 }
6257
Alexey Bataev475a7442018-01-12 19:39:11 +00006258 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006259
Samuel Antaobed3c462015-10-02 16:14:20 +00006260 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006261 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006262 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006263
Samuel Antao6d004262016-06-16 18:39:34 +00006264 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006265
6266 // If this target outline function is not an offload entry, we don't need to
6267 // register it.
6268 if (!IsOffloadEntry)
6269 return;
6270
6271 // The target region ID is used by the runtime library to identify the current
6272 // target region, so it only has to be unique and not necessarily point to
6273 // anything. It could be the pointer to the outlined function that implements
6274 // the target region, but we aren't using that so that the compiler doesn't
6275 // need to keep that, and could therefore inline the host function if proven
6276 // worthwhile during optimization. In the other hand, if emitting code for the
6277 // device, the ID has to be the function address so that it can retrieved from
6278 // the offloading entry and launched by the runtime library. We also mark the
6279 // outlined function to have external linkage in case we are emitting code for
6280 // the device, because these functions will be entry points to the device.
6281
6282 if (CGM.getLangOpts().OpenMPIsDevice) {
6283 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006284 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006285 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006286 } else {
Alexey Bataev18fa2322018-05-02 14:20:50 +00006287 std::string Name = getName({"omp_offload", "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006288 OutlinedFnID = new llvm::GlobalVariable(
6289 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006290 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006291 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006292 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006293
6294 // Register the information for the entry associated with this target region.
6295 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006296 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006297 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006298}
6299
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006300/// discard all CompoundStmts intervening between two constructs
6301static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006302 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006303 Body = CS->body_front();
6304
6305 return Body;
6306}
6307
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006308/// Emit the number of teams for a target directive. Inspect the num_teams
6309/// clause associated with a teams construct combined or closely nested
6310/// with the target directive.
6311///
6312/// Emit a team of size one for directives such as 'target parallel' that
6313/// have no associated teams construct.
6314///
6315/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006316static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006317emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6318 CodeGenFunction &CGF,
6319 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006320 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6321 "teams directive expected to be "
6322 "emitted only for the host!");
6323
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006324 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006325
6326 // If the target directive is combined with a teams directive:
6327 // Return the value in the num_teams clause, if any.
6328 // Otherwise, return 0 to denote the runtime default.
6329 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6330 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6331 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006332 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6333 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006334 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6335 /*IsSigned=*/true);
6336 }
6337
6338 // The default value is 0.
6339 return Bld.getInt32(0);
6340 }
6341
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006342 // If the target directive is combined with a parallel directive but not a
6343 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006344 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6345 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006346
6347 // If the current target region has a teams region enclosed, we need to get
6348 // the number of teams to pass to the runtime function call. This is done
6349 // by generating the expression in a inlined region. This is required because
6350 // the expression is captured in the enclosing target environment when the
6351 // teams directive is not combined with target.
6352
Alexey Bataev475a7442018-01-12 19:39:11 +00006353 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006354
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006355 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006356 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006357 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006358 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006359 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6360 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6361 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6362 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6363 /*IsSigned=*/true);
6364 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006365
Alexey Bataev50a1c782017-12-01 21:31:08 +00006366 // If we have an enclosed teams directive but no num_teams clause we use
6367 // the default value 0.
6368 return Bld.getInt32(0);
6369 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006370 }
6371
6372 // No teams associated with the directive.
6373 return nullptr;
6374}
6375
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006376/// Emit the number of threads for a target directive. Inspect the
6377/// thread_limit clause associated with a teams construct combined or closely
6378/// nested with the target directive.
6379///
6380/// Emit the num_threads clause for directives such as 'target parallel' that
6381/// have no associated teams construct.
6382///
6383/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006384static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006385emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6386 CodeGenFunction &CGF,
6387 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006388 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6389 "teams directive expected to be "
6390 "emitted only for the host!");
6391
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006392 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006393
6394 //
6395 // If the target directive is combined with a teams directive:
6396 // Return the value in the thread_limit clause, if any.
6397 //
6398 // If the target directive is combined with a parallel directive:
6399 // Return the value in the num_threads clause, if any.
6400 //
6401 // If both clauses are set, select the minimum of the two.
6402 //
6403 // If neither teams or parallel combined directives set the number of threads
6404 // in a team, return 0 to denote the runtime default.
6405 //
6406 // If this is not a teams directive return nullptr.
6407
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006408 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6409 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006410 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6411 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006412 llvm::Value *ThreadLimitVal = nullptr;
6413
6414 if (const auto *ThreadLimitClause =
6415 D.getSingleClause<OMPThreadLimitClause>()) {
6416 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006417 llvm::Value *ThreadLimit =
6418 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6419 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006420 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6421 /*IsSigned=*/true);
6422 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006423
6424 if (const auto *NumThreadsClause =
6425 D.getSingleClause<OMPNumThreadsClause>()) {
6426 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6427 llvm::Value *NumThreads =
6428 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6429 /*IgnoreResultAssign*/ true);
6430 NumThreadsVal =
6431 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6432 }
6433
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006434 // Select the lesser of thread_limit and num_threads.
6435 if (NumThreadsVal)
6436 ThreadLimitVal = ThreadLimitVal
6437 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6438 ThreadLimitVal),
6439 NumThreadsVal, ThreadLimitVal)
6440 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006441
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006442 // Set default value passed to the runtime if either teams or a target
6443 // parallel type directive is found but no clause is specified.
6444 if (!ThreadLimitVal)
6445 ThreadLimitVal = DefaultThreadLimitVal;
6446
6447 return ThreadLimitVal;
6448 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006449
Samuel Antaob68e2db2016-03-03 16:20:23 +00006450 // If the current target region has a teams region enclosed, we need to get
6451 // the thread limit to pass to the runtime function call. This is done
6452 // by generating the expression in a inlined region. This is required because
6453 // the expression is captured in the enclosing target environment when the
6454 // teams directive is not combined with target.
6455
Alexey Bataev475a7442018-01-12 19:39:11 +00006456 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006457
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006458 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006459 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006460 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006461 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006462 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6463 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6464 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6465 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6466 /*IsSigned=*/true);
6467 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006468
Alexey Bataev50a1c782017-12-01 21:31:08 +00006469 // If we have an enclosed teams directive but no thread_limit clause we
6470 // use the default value 0.
6471 return CGF.Builder.getInt32(0);
6472 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006473 }
6474
6475 // No teams associated with the directive.
6476 return nullptr;
6477}
6478
Samuel Antao86ace552016-04-27 22:40:57 +00006479namespace {
6480// \brief Utility to handle information from clauses associated with a given
6481// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6482// It provides a convenient interface to obtain the information and generate
6483// code for that information.
6484class MappableExprsHandler {
6485public:
6486 /// \brief Values for bit flags used to specify the mapping type for
6487 /// offloading.
6488 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006489 /// \brief Allocate memory on the device and move data from host to device.
6490 OMP_MAP_TO = 0x01,
6491 /// \brief Allocate memory on the device and move data from device to host.
6492 OMP_MAP_FROM = 0x02,
6493 /// \brief Always perform the requested mapping action on the element, even
6494 /// if it was already mapped before.
6495 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006496 /// \brief Delete the element from the device environment, ignoring the
6497 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006498 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006499 /// \brief The element being mapped is a pointer-pointee pair; both the
6500 /// pointer and the pointee should be mapped.
6501 OMP_MAP_PTR_AND_OBJ = 0x10,
6502 /// \brief This flags signals that the base address of an entry should be
6503 /// passed to the target kernel as an argument.
6504 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006505 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006506 /// in the current position for the data being mapped. Used when we have the
6507 /// use_device_ptr clause.
6508 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006509 /// \brief This flag signals that the reference being passed is a pointer to
6510 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006511 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006512 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006513 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006514 /// Implicit map
6515 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006516 };
6517
Samuel Antaocc10b852016-07-28 14:23:26 +00006518 /// Class that associates information with a base pointer to be passed to the
6519 /// runtime library.
6520 class BasePointerInfo {
6521 /// The base pointer.
6522 llvm::Value *Ptr = nullptr;
6523 /// The base declaration that refers to this device pointer, or null if
6524 /// there is none.
6525 const ValueDecl *DevPtrDecl = nullptr;
6526
6527 public:
6528 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6529 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6530 llvm::Value *operator*() const { return Ptr; }
6531 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6532 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6533 };
6534
6535 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006536 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006537 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006538
6539private:
6540 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006541 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006542
6543 /// \brief Function the directive is being generated for.
6544 CodeGenFunction &CGF;
6545
Samuel Antaod486f842016-05-26 16:53:38 +00006546 /// \brief Set of all first private variables in the current directive.
6547 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006548 /// Set of all reduction variables in the current directive.
6549 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006550
Samuel Antao6890b092016-07-28 14:25:09 +00006551 /// Map between device pointer declarations and their expression components.
6552 /// The key value for declarations in 'this' is null.
6553 llvm::DenseMap<
6554 const ValueDecl *,
6555 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6556 DevPointersMap;
6557
Samuel Antao86ace552016-04-27 22:40:57 +00006558 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006559 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006560
6561 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006562 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006563 ExprTy = RefTy->getPointeeType().getCanonicalType();
6564
6565 // Given that an array section is considered a built-in type, we need to
6566 // do the calculation based on the length of the section instead of relying
6567 // on CGF.getTypeSize(E->getType()).
6568 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6569 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6570 OAE->getBase()->IgnoreParenImpCasts())
6571 .getCanonicalType();
6572
6573 // If there is no length associated with the expression, that means we
6574 // are using the whole length of the base.
6575 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6576 return CGF.getTypeSize(BaseTy);
6577
6578 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006579 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006580 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006581 } else {
6582 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006583 assert(ATy && "Expecting array type if not a pointer type.");
6584 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6585 }
6586
6587 // If we don't have a length at this point, that is because we have an
6588 // array section with a single element.
6589 if (!OAE->getLength())
6590 return ElemSize;
6591
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006592 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006593 LengthVal =
6594 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6595 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6596 }
6597 return CGF.getTypeSize(ExprTy);
6598 }
6599
6600 /// \brief Return the corresponding bits for a given map clause modifier. Add
6601 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006602 /// map as the first one of a series of maps that relate to the same map
6603 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006604 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006605 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006606 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006607 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006608 switch (MapType) {
6609 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006610 case OMPC_MAP_release:
6611 // alloc and release is the default behavior in the runtime library, i.e.
6612 // if we don't pass any bits alloc/release that is what the runtime is
6613 // going to do. Therefore, we don't need to signal anything for these two
6614 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006615 break;
6616 case OMPC_MAP_to:
6617 Bits = OMP_MAP_TO;
6618 break;
6619 case OMPC_MAP_from:
6620 Bits = OMP_MAP_FROM;
6621 break;
6622 case OMPC_MAP_tofrom:
6623 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6624 break;
6625 case OMPC_MAP_delete:
6626 Bits = OMP_MAP_DELETE;
6627 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006628 default:
6629 llvm_unreachable("Unexpected map type!");
6630 break;
6631 }
6632 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006633 Bits |= OMP_MAP_PTR_AND_OBJ;
6634 if (AddIsTargetParamFlag)
6635 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006636 if (MapTypeModifier == OMPC_MAP_always)
6637 Bits |= OMP_MAP_ALWAYS;
6638 return Bits;
6639 }
6640
6641 /// \brief Return true if the provided expression is a final array section. A
6642 /// final array section, is one whose length can't be proved to be one.
6643 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006644 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006645
6646 // It is not an array section and therefore not a unity-size one.
6647 if (!OASE)
6648 return false;
6649
6650 // An array section with no colon always refer to a single element.
6651 if (OASE->getColonLoc().isInvalid())
6652 return false;
6653
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006654 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006655
6656 // If we don't have a length we have to check if the array has size 1
6657 // for this dimension. Also, we should always expect a length if the
6658 // base type is pointer.
6659 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006660 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6661 OASE->getBase()->IgnoreParenImpCasts())
6662 .getCanonicalType();
6663 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006664 return ATy->getSize().getSExtValue() != 1;
6665 // If we don't have a constant dimension length, we have to consider
6666 // the current section as having any size, so it is not necessarily
6667 // unitary. If it happen to be unity size, that's user fault.
6668 return true;
6669 }
6670
6671 // Check if the length evaluates to 1.
6672 llvm::APSInt ConstLength;
6673 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6674 return true; // Can have more that size 1.
6675
6676 return ConstLength.getSExtValue() != 1;
6677 }
6678
Alexey Bataev92327c52018-03-26 16:40:55 +00006679 /// \brief Return the adjusted map modifiers if the declaration a capture
6680 /// refers to appears in a first-private clause. This is expected to be used
6681 /// only with directives that start with 'target'.
6682 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6683 unsigned CurrentModifiers) {
6684 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6685
6686 // A first private variable captured by reference will use only the
6687 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6688 // declaration is known as first-private in this handler.
6689 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6690 return MappableExprsHandler::OMP_MAP_PRIVATE |
6691 MappableExprsHandler::OMP_MAP_TO;
6692 // Reduction variable will use only the 'private ptr' and 'map to_from'
6693 // flag.
6694 if (ReductionDecls.count(Cap.getCapturedVar())) {
6695 return MappableExprsHandler::OMP_MAP_TO |
6696 MappableExprsHandler::OMP_MAP_FROM;
6697 }
6698
6699 // We didn't modify anything.
6700 return CurrentModifiers;
6701 }
6702
6703public:
6704 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6705 : CurDir(Dir), CGF(CGF) {
6706 // Extract firstprivate clause information.
6707 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006708 for (const Expr *D : C->varlists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006709 FirstPrivateDecls.insert(
6710 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6711 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006712 for (const Expr *D : C->varlists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00006713 ReductionDecls.insert(
6714 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6715 }
6716 }
6717 // Extract device pointer clause information.
6718 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006719 for (const auto &L : C->component_lists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006720 DevPointersMap[L.first].push_back(L.second);
6721 }
6722
Samuel Antao86ace552016-04-27 22:40:57 +00006723 /// \brief Generate the base pointers, section pointers, sizes and map type
6724 /// bits for the provided map type, map modifier, and expression components.
6725 /// \a IsFirstComponent should be set to true if the provided set of
6726 /// components is the first associated with a capture.
6727 void generateInfoForComponentList(
6728 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6729 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006730 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006731 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006732 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006733
6734 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006735 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006736 // base pointer, section pointer, size, flags
6737 // (to add to the ones that come from the map type and modifier).
6738 //
6739 // double d;
6740 // int i[100];
6741 // float *p;
6742 //
6743 // struct S1 {
6744 // int i;
6745 // float f[50];
6746 // }
6747 // struct S2 {
6748 // int i;
6749 // float f[50];
6750 // S1 s;
6751 // double *p;
6752 // struct S2 *ps;
6753 // }
6754 // S2 s;
6755 // S2 *ps;
6756 //
6757 // map(d)
6758 // &d, &d, sizeof(double), noflags
6759 //
6760 // map(i)
6761 // &i, &i, 100*sizeof(int), noflags
6762 //
6763 // map(i[1:23])
6764 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6765 //
6766 // map(p)
6767 // &p, &p, sizeof(float*), noflags
6768 //
6769 // map(p[1:24])
6770 // p, &p[1], 24*sizeof(float), noflags
6771 //
6772 // map(s)
6773 // &s, &s, sizeof(S2), noflags
6774 //
6775 // map(s.i)
6776 // &s, &(s.i), sizeof(int), noflags
6777 //
6778 // map(s.s.f)
6779 // &s, &(s.i.f), 50*sizeof(int), noflags
6780 //
6781 // map(s.p)
6782 // &s, &(s.p), sizeof(double*), noflags
6783 //
6784 // map(s.p[:22], s.a s.b)
6785 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006786 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006787 //
6788 // map(s.ps)
6789 // &s, &(s.ps), sizeof(S2*), noflags
6790 //
6791 // map(s.ps->s.i)
6792 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006793 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006794 //
6795 // map(s.ps->ps)
6796 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006797 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006798 //
6799 // map(s.ps->ps->ps)
6800 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006801 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6802 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006803 //
6804 // map(s.ps->ps->s.f[:22])
6805 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006806 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6807 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006808 //
6809 // map(ps)
6810 // &ps, &ps, sizeof(S2*), noflags
6811 //
6812 // map(ps->i)
6813 // ps, &(ps->i), sizeof(int), noflags
6814 //
6815 // map(ps->s.f)
6816 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6817 //
6818 // map(ps->p)
6819 // ps, &(ps->p), sizeof(double*), noflags
6820 //
6821 // map(ps->p[:22])
6822 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006823 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006824 //
6825 // map(ps->ps)
6826 // ps, &(ps->ps), sizeof(S2*), noflags
6827 //
6828 // map(ps->ps->s.i)
6829 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006830 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006831 //
6832 // map(ps->ps->ps)
6833 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006834 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006835 //
6836 // map(ps->ps->ps->ps)
6837 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006838 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6839 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006840 //
6841 // map(ps->ps->ps->s.f[:22])
6842 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006843 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6844 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006845
6846 // Track if the map information being generated is the first for a capture.
6847 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006848 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006849
6850 // Scan the components from the base to the complete expression.
6851 auto CI = Components.rbegin();
6852 auto CE = Components.rend();
6853 auto I = CI;
6854
6855 // Track if the map information being generated is the first for a list of
6856 // components.
6857 bool IsExpressionFirstInfo = true;
6858 llvm::Value *BP = nullptr;
6859
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006860 if (const auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006861 // The base is the 'this' pointer. The content of the pointer is going
6862 // to be the base of the field being mapped.
6863 BP = CGF.EmitScalarExpr(ME->getBase());
6864 } else {
6865 // The base is the reference to the variable.
6866 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006867 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataev92327c52018-03-26 16:40:55 +00006868 if (const auto *VD =
6869 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6870 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006871 isDeclareTargetDeclaration(VD))
6872 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6873 IsLink = true;
6874 BP = CGF.CGM.getOpenMPRuntime()
6875 .getAddrOfDeclareTargetLink(VD)
6876 .getPointer();
6877 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006878 }
Samuel Antao86ace552016-04-27 22:40:57 +00006879
6880 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006881 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006882 // reference. References are ignored for mapping purposes.
6883 QualType Ty =
6884 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6885 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006886 LValue PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006887 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006888 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006889 .getPointer();
6890
6891 // We do not need to generate individual map information for the
6892 // pointer, it can be associated with the combined storage.
6893 ++I;
6894 }
6895 }
6896
George Rokos63bc9d62017-11-21 18:25:12 +00006897 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006898 for (; I != CE; ++I) {
6899 auto Next = std::next(I);
6900
6901 // We need to generate the addresses and sizes if this is the last
6902 // component, if the component is a pointer or if it is an array section
6903 // whose length can't be proved to be one. If this is a pointer, it
6904 // becomes the base address for the following components.
6905
6906 // A final array section, is one whose length can't be proved to be one.
6907 bool IsFinalArraySection =
6908 isFinalArraySectionExpression(I->getAssociatedExpression());
6909
6910 // Get information on whether the element is a pointer. Have to do a
6911 // special treatment for array sections given that they are built-in
6912 // types.
6913 const auto *OASE =
6914 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6915 bool IsPointer =
6916 (OASE &&
6917 OMPArraySectionExpr::getBaseOriginalType(OASE)
6918 .getCanonicalType()
6919 ->isAnyPointerType()) ||
6920 I->getAssociatedExpression()->getType()->isAnyPointerType();
6921
6922 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00006923 // If this is not the last component, we expect the pointer to be
6924 // associated with an array expression or member expression.
6925 assert((Next == CE ||
6926 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6927 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6928 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6929 "Unexpected expression");
6930
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006931 llvm::Value *LB =
6932 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006933 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Samuel Antao86ace552016-04-27 22:40:57 +00006934
Samuel Antao03a3cec2016-07-27 22:52:16 +00006935 // If we have a member expression and the current component is a
6936 // reference, we have to map the reference too. Whenever we have a
6937 // reference, the section that reference refers to is going to be a
6938 // load instruction from the storage assigned to the reference.
6939 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6940 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6941 auto *LI = cast<llvm::LoadInst>(LB);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006942 llvm::Value *RefAddr = LI->getPointerOperand();
Samuel Antao03a3cec2016-07-27 22:52:16 +00006943
6944 BasePointers.push_back(BP);
6945 Pointers.push_back(RefAddr);
6946 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006947 Types.push_back(DefaultFlags |
6948 getMapTypeBits(
6949 /*MapType*/ OMPC_MAP_alloc,
6950 /*MapTypeModifier=*/OMPC_MAP_unknown,
6951 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006952 IsExpressionFirstInfo = false;
6953 IsCaptureFirstInfo = false;
6954 // The reference will be the next base address.
6955 BP = RefAddr;
6956 }
6957
6958 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006959 Pointers.push_back(LB);
6960 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006961
Samuel Antao6782e942016-05-26 16:48:10 +00006962 // We need to add a pointer flag for each map that comes from the
6963 // same expression except for the first one. We also need to signal
6964 // this map is the first one that relates with the current capture
6965 // (there is a set of entries for each capture).
Alexey Bataev92327c52018-03-26 16:40:55 +00006966 Types.push_back(DefaultFlags |
6967 getMapTypeBits(MapType, MapTypeModifier,
6968 !IsExpressionFirstInfo || IsLink,
6969 IsCaptureFirstInfo && !IsLink));
Samuel Antao86ace552016-04-27 22:40:57 +00006970
6971 // If we have a final array section, we are done with this expression.
6972 if (IsFinalArraySection)
6973 break;
6974
6975 // The pointer becomes the base for the next element.
6976 if (Next != CE)
6977 BP = LB;
6978
6979 IsExpressionFirstInfo = false;
6980 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006981 }
6982 }
6983 }
6984
Samuel Antao86ace552016-04-27 22:40:57 +00006985 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006986 /// types for the extracted mappable expressions. Also, for each item that
6987 /// relates with a device pointer, a pair of the relevant declaration and
6988 /// index where it occurs is appended to the device pointers info array.
6989 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006990 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6991 MapFlagsArrayTy &Types) const {
6992 BasePointers.clear();
6993 Pointers.clear();
6994 Sizes.clear();
6995 Types.clear();
6996
6997 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006998 /// Kind that defines how a device pointer has to be returned.
6999 enum ReturnPointerKind {
7000 // Don't have to return any pointer.
7001 RPK_None,
7002 // Pointer is the base of the declaration.
7003 RPK_Base,
7004 // Pointer is a member of the base declaration - 'this'
7005 RPK_Member,
7006 // Pointer is a reference and a member of the base declaration - 'this'
7007 RPK_MemberReference,
7008 };
Samuel Antao86ace552016-04-27 22:40:57 +00007009 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007010 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
7011 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
7012 ReturnPointerKind ReturnDevicePointer = RPK_None;
7013 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00007014
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007015 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00007016 MapInfo(
7017 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
7018 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007019 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00007020 : Components(Components), MapType(MapType),
7021 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007022 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00007023 };
7024
7025 // We have to process the component lists that relate with the same
7026 // declaration in a single chunk so that we can generate the map flags
7027 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007028 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007029
7030 // Helper function to fill the information map for the different supported
7031 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007032 auto &&InfoGen = [&Info](
7033 const ValueDecl *D,
7034 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7035 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007036 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007037 const ValueDecl *VD =
7038 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007039 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7040 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007041 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007042
Paul Robinson78fb1322016-08-01 22:12:46 +00007043 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007044 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7045 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007046 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007047 MapInfo::RPK_None, C->isImplicit());
7048 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007049 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7050 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007051 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007052 MapInfo::RPK_None, C->isImplicit());
7053 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007054 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7055 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007056 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007057 MapInfo::RPK_None, C->isImplicit());
7058 }
Samuel Antao86ace552016-04-27 22:40:57 +00007059
Samuel Antaocc10b852016-07-28 14:23:26 +00007060 // Look at the use_device_ptr clause information and mark the existing map
7061 // entries as such. If there is no map information for an entry in the
7062 // use_device_ptr list, we create one with map type 'alloc' and zero size
7063 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00007064 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007065 for (const auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
7066 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007067 assert(!L.second.empty() && "Not expecting empty list of components!");
7068 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7069 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007070 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007071 // If the first component is a member expression, we have to look into
7072 // 'this', which maps to null in the map of map information. Otherwise
7073 // look directly for the information.
7074 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7075
7076 // We potentially have map information for this declaration already.
7077 // Look for the first set of components that refer to it.
7078 if (It != Info.end()) {
7079 auto CI = std::find_if(
7080 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7081 return MI.Components.back().getAssociatedDeclaration() == VD;
7082 });
7083 // If we found a map entry, signal that the pointer has to be returned
7084 // and move on to the next declaration.
7085 if (CI != It->second.end()) {
7086 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
7087 ? (VD->getType()->isReferenceType()
7088 ? MapInfo::RPK_MemberReference
7089 : MapInfo::RPK_Member)
7090 : MapInfo::RPK_Base;
7091 continue;
7092 }
7093 }
7094
7095 // We didn't find any match in our map information - generate a zero
7096 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00007097 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00007098 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
7099 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00007100 BasePointers.push_back({Ptr, VD});
7101 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00007102 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00007103 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00007104 }
7105
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007106 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007107 // We need to know when we generate information for the first component
7108 // associated with a capture, because the mapping flags depend on it.
7109 bool IsFirstComponentList = true;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007110 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007111 assert(!L.Components.empty() &&
7112 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007113
7114 // Remember the current base pointer index.
7115 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007116 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007117 this->generateInfoForComponentList(
7118 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
7119 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007120
7121 // If this entry relates with a device pointer, set the relevant
7122 // declaration and add the 'return pointer' flag.
7123 if (IsFirstComponentList &&
7124 L.ReturnDevicePointer != MapInfo::RPK_None) {
7125 // If the pointer is not the base of the map, we need to skip the
7126 // base. If it is a reference in a member field, we also need to skip
7127 // the map of the reference.
7128 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
7129 ++CurrentBasePointersIdx;
7130 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
7131 ++CurrentBasePointersIdx;
7132 }
7133 assert(BasePointers.size() > CurrentBasePointersIdx &&
7134 "Unexpected number of mapped base pointers.");
7135
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007136 const ValueDecl *RelevantVD =
7137 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007138 assert(RelevantVD &&
7139 "No relevant declaration related with device pointer??");
7140
7141 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00007142 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007143 }
Samuel Antao86ace552016-04-27 22:40:57 +00007144 IsFirstComponentList = false;
7145 }
7146 }
7147 }
7148
7149 /// \brief Generate the base pointers, section pointers, sizes and map types
7150 /// associated to a given capture.
7151 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007152 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007153 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007154 MapValuesArrayTy &Pointers,
7155 MapValuesArrayTy &Sizes,
7156 MapFlagsArrayTy &Types) const {
7157 assert(!Cap->capturesVariableArrayType() &&
7158 "Not expecting to generate map info for a variable array type!");
7159
7160 BasePointers.clear();
7161 Pointers.clear();
7162 Sizes.clear();
7163 Types.clear();
7164
Samuel Antao6890b092016-07-28 14:25:09 +00007165 // We need to know when we generating information for the first component
7166 // associated with a capture, because the mapping flags depend on it.
7167 bool IsFirstComponentList = true;
7168
Samuel Antao86ace552016-04-27 22:40:57 +00007169 const ValueDecl *VD =
7170 Cap->capturesThis()
7171 ? nullptr
George Burgess IV00f70bd2018-03-01 05:43:23 +00007172 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007173
Samuel Antao6890b092016-07-28 14:25:09 +00007174 // If this declaration appears in a is_device_ptr clause we just have to
7175 // pass the pointer by value. If it is a reference to a declaration, we just
7176 // pass its value, otherwise, if it is a member expression, we need to map
7177 // 'to' the field.
7178 if (!VD) {
7179 auto It = DevPointersMap.find(VD);
7180 if (It != DevPointersMap.end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007181 for (ArrayRef<OMPClauseMappableExprCommon::MappableComponent> L :
7182 It->second) {
Samuel Antao6890b092016-07-28 14:25:09 +00007183 generateInfoForComponentList(
7184 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007185 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
7186 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00007187 IsFirstComponentList = false;
7188 }
7189 return;
7190 }
7191 } else if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007192 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007193 Pointers.push_back(Arg);
7194 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007195 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007196 return;
7197 }
7198
Paul Robinson78fb1322016-08-01 22:12:46 +00007199 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007200 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7201 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007202 assert(L.first == VD &&
7203 "We got information for the wrong declaration??");
7204 assert(!L.second.empty() &&
7205 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007206 generateInfoForComponentList(
7207 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7208 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007209 IsFirstComponentList = false;
7210 }
7211
7212 return;
7213 }
Samuel Antaod486f842016-05-26 16:53:38 +00007214
7215 /// \brief Generate the default map information for a given capture \a CI,
7216 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007217 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7218 const FieldDecl &RI, llvm::Value *CV,
7219 MapBaseValuesArrayTy &CurBasePointers,
7220 MapValuesArrayTy &CurPointers,
7221 MapValuesArrayTy &CurSizes,
7222 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00007223
7224 // Do the default mapping.
7225 if (CI.capturesThis()) {
7226 CurBasePointers.push_back(CV);
7227 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007228 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007229 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7230 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007231 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007232 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007233 CurBasePointers.push_back(CV);
7234 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007235 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007236 // We have to signal to the runtime captures passed by value that are
7237 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007238 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007239 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7240 } else {
7241 // Pointers are implicitly mapped with a zero size and no flags
7242 // (other than first map that is added for all implicit maps).
7243 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00007244 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7245 }
7246 } else {
7247 assert(CI.capturesVariable() && "Expected captured reference.");
7248 CurBasePointers.push_back(CV);
7249 CurPointers.push_back(CV);
7250
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007251 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007252 QualType ElementType = PtrTy->getPointeeType();
7253 CurSizes.push_back(CGF.getTypeSize(ElementType));
7254 // The default map type for a scalar/complex type is 'to' because by
7255 // default the value doesn't have to be retrieved. For an aggregate
7256 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00007257 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
7258 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
7259 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00007260 }
George Rokos065755d2017-11-07 18:27:04 +00007261 // Every default map produces a single argument which is a target parameter.
7262 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00007263 }
Samuel Antao86ace552016-04-27 22:40:57 +00007264};
Samuel Antaodf158d52016-04-27 22:58:19 +00007265
7266enum OpenMPOffloadingReservedDeviceIDs {
7267 /// \brief Device ID if the device was not defined, runtime should get it
7268 /// from environment variables in the spec.
7269 OMP_DEVICEID_UNDEF = -1,
7270};
7271} // anonymous namespace
7272
7273/// \brief Emit the arrays used to pass the captures and map information to the
7274/// offloading runtime library. If there is no map or capture information,
7275/// return nullptr by reference.
7276static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007277emitOffloadingArrays(CodeGenFunction &CGF,
7278 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007279 MappableExprsHandler::MapValuesArrayTy &Pointers,
7280 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007281 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7282 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007283 CodeGenModule &CGM = CGF.CGM;
7284 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007285
Samuel Antaocc10b852016-07-28 14:23:26 +00007286 // Reset the array information.
7287 Info.clearArrayInfo();
7288 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007289
Samuel Antaocc10b852016-07-28 14:23:26 +00007290 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007291 // Detect if we have any capture size requiring runtime evaluation of the
7292 // size so that a constant array could be eventually used.
7293 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007294 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007295 if (!isa<llvm::Constant>(S)) {
7296 hasRuntimeEvaluationCaptureSize = true;
7297 break;
7298 }
7299
Samuel Antaocc10b852016-07-28 14:23:26 +00007300 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007301 QualType PointerArrayType =
7302 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7303 /*IndexTypeQuals=*/0);
7304
Samuel Antaocc10b852016-07-28 14:23:26 +00007305 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007306 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007307 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007308 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7309
7310 // If we don't have any VLA types or other types that require runtime
7311 // evaluation, we can use a constant array for the map sizes, otherwise we
7312 // need to fill up the arrays as we do for the pointers.
7313 if (hasRuntimeEvaluationCaptureSize) {
7314 QualType SizeArrayType = Ctx.getConstantArrayType(
7315 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7316 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007317 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007318 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7319 } else {
7320 // We expect all the sizes to be constant, so we collect them to create
7321 // a constant array.
7322 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007323 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007324 ConstSizes.push_back(cast<llvm::Constant>(S));
7325
7326 auto *SizesArrayInit = llvm::ConstantArray::get(
7327 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007328 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007329 auto *SizesArrayGbl = new llvm::GlobalVariable(
7330 CGM.getModule(), SizesArrayInit->getType(),
7331 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007332 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007333 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007334 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007335 }
7336
7337 // The map types are always constant so we don't need to generate code to
7338 // fill arrays. Instead, we create an array constant.
7339 llvm::Constant *MapTypesArrayInit =
7340 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007341 std::string MaptypesName =
7342 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007343 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7344 CGM.getModule(), MapTypesArrayInit->getType(),
7345 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007346 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007347 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007348 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007349
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007350 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7351 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007352 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007353 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007354 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007355 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7356 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007357 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7358 CGF.Builder.CreateStore(BPVal, BPAddr);
7359
Samuel Antaocc10b852016-07-28 14:23:26 +00007360 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007361 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007362 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007363
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007364 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007365 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007366 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007367 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007368 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7369 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007370 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7371 CGF.Builder.CreateStore(PVal, PAddr);
7372
7373 if (hasRuntimeEvaluationCaptureSize) {
7374 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007375 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7376 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007377 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007378 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007379 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7380 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007381 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007382 SAddr);
7383 }
7384 }
7385 }
7386}
7387/// \brief Emit the arguments to be passed to the runtime library based on the
7388/// arrays of pointers, sizes and map types.
7389static void emitOffloadingArraysArgument(
7390 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7391 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007392 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007393 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007394 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007395 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007396 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7397 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007398 /*Idx0=*/0, /*Idx1=*/0);
7399 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007400 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7401 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007402 /*Idx0=*/0,
7403 /*Idx1=*/0);
7404 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007405 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007406 /*Idx0=*/0, /*Idx1=*/0);
7407 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007408 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007409 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007410 /*Idx0=*/0,
7411 /*Idx1=*/0);
7412 } else {
7413 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7414 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7415 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7416 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007417 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007418 }
Samuel Antao86ace552016-04-27 22:40:57 +00007419}
7420
Samuel Antaobed3c462015-10-02 16:14:20 +00007421void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7422 const OMPExecutableDirective &D,
7423 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007424 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007425 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007426 if (!CGF.HaveInsertPoint())
7427 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007428
Samuel Antaoee8fb302016-01-06 13:42:12 +00007429 assert(OutlinedFn && "Invalid outlined function!");
7430
Alexey Bataev8451efa2018-01-15 19:06:12 +00007431 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7432 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007433 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007434 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7435 PrePostActionTy &) {
7436 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7437 };
7438 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007439
Alexey Bataev8451efa2018-01-15 19:06:12 +00007440 CodeGenFunction::OMPTargetDataInfo InputInfo;
7441 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007442 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007443 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7444 &MapTypesArray, &CS, RequiresOuterTask,
7445 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007446 // On top of the arrays that were filled up, the target offloading call
7447 // takes as arguments the device id as well as the host pointer. The host
7448 // pointer is used by the runtime library to identify the current target
7449 // region, so it only has to be unique and not necessarily point to
7450 // anything. It could be the pointer to the outlined function that
7451 // implements the target region, but we aren't using that so that the
7452 // compiler doesn't need to keep that, and could therefore inline the host
7453 // function if proven worthwhile during optimization.
7454
Samuel Antaoee8fb302016-01-06 13:42:12 +00007455 // From this point on, we need to have an ID of the target region defined.
7456 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007457
7458 // Emit device ID if any.
7459 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007460 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007461 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007462 CGF.Int64Ty, /*isSigned=*/true);
7463 } else {
7464 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7465 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007466
Samuel Antaodf158d52016-04-27 22:58:19 +00007467 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007468 llvm::Value *PointerNum =
7469 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007470
Samuel Antaob68e2db2016-03-03 16:20:23 +00007471 // Return value of the runtime offloading call.
7472 llvm::Value *Return;
7473
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007474 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7475 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007476
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007477 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007478 // The target region is an outlined function launched by the runtime
7479 // via calls __tgt_target() or __tgt_target_teams().
7480 //
7481 // __tgt_target() launches a target region with one team and one thread,
7482 // executing a serial region. This master thread may in turn launch
7483 // more threads within its team upon encountering a parallel region,
7484 // however, no additional teams can be launched on the device.
7485 //
7486 // __tgt_target_teams() launches a target region with one or more teams,
7487 // each with one or more threads. This call is required for target
7488 // constructs such as:
7489 // 'target teams'
7490 // 'target' / 'teams'
7491 // 'target teams distribute parallel for'
7492 // 'target parallel'
7493 // and so on.
7494 //
7495 // Note that on the host and CPU targets, the runtime implementation of
7496 // these calls simply call the outlined function without forking threads.
7497 // The outlined functions themselves have runtime calls to
7498 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7499 // the compiler in emitTeamsCall() and emitParallelCall().
7500 //
7501 // In contrast, on the NVPTX target, the implementation of
7502 // __tgt_target_teams() launches a GPU kernel with the requested number
7503 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007504 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007505 // If we have NumTeams defined this means that we have an enclosed teams
7506 // region. Therefore we also expect to have NumThreads defined. These two
7507 // values should be defined in the presence of a teams directive,
7508 // regardless of having any clauses associated. If the user is using teams
7509 // but no clauses, these two values will be the default that should be
7510 // passed to the runtime library - a 32-bit integer with the value zero.
7511 assert(NumThreads && "Thread limit expression should be available along "
7512 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007513 llvm::Value *OffloadingArgs[] = {DeviceID,
7514 OutlinedFnID,
7515 PointerNum,
7516 InputInfo.BasePointersArray.getPointer(),
7517 InputInfo.PointersArray.getPointer(),
7518 InputInfo.SizesArray.getPointer(),
7519 MapTypesArray,
7520 NumTeams,
7521 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007522 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007523 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7524 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007525 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007526 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007527 llvm::Value *OffloadingArgs[] = {DeviceID,
7528 OutlinedFnID,
7529 PointerNum,
7530 InputInfo.BasePointersArray.getPointer(),
7531 InputInfo.PointersArray.getPointer(),
7532 InputInfo.SizesArray.getPointer(),
7533 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007534 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007535 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7536 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007537 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007538 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007539
Alexey Bataev2a007e02017-10-02 14:20:58 +00007540 // Check the error code and execute the host version if required.
7541 llvm::BasicBlock *OffloadFailedBlock =
7542 CGF.createBasicBlock("omp_offload.failed");
7543 llvm::BasicBlock *OffloadContBlock =
7544 CGF.createBasicBlock("omp_offload.cont");
7545 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7546 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7547
7548 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007549 if (RequiresOuterTask) {
7550 CapturedVars.clear();
7551 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7552 }
7553 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007554 CGF.EmitBranch(OffloadContBlock);
7555
7556 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007557 };
7558
Samuel Antaoee8fb302016-01-06 13:42:12 +00007559 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007560 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7561 RequiresOuterTask](CodeGenFunction &CGF,
7562 PrePostActionTy &) {
7563 if (RequiresOuterTask) {
7564 CapturedVars.clear();
7565 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7566 }
7567 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7568 };
7569
7570 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7571 &CapturedVars, RequiresOuterTask,
7572 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7573 // Fill up the arrays with all the captured variables.
7574 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7575 MappableExprsHandler::MapValuesArrayTy Pointers;
7576 MappableExprsHandler::MapValuesArrayTy Sizes;
7577 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7578
7579 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7580 MappableExprsHandler::MapValuesArrayTy CurPointers;
7581 MappableExprsHandler::MapValuesArrayTy CurSizes;
7582 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7583
7584 // Get mappable expression information.
7585 MappableExprsHandler MEHandler(D, CGF);
7586
7587 auto RI = CS.getCapturedRecordDecl()->field_begin();
7588 auto CV = CapturedVars.begin();
7589 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7590 CE = CS.capture_end();
7591 CI != CE; ++CI, ++RI, ++CV) {
7592 CurBasePointers.clear();
7593 CurPointers.clear();
7594 CurSizes.clear();
7595 CurMapTypes.clear();
7596
7597 // VLA sizes are passed to the outlined region by copy and do not have map
7598 // information associated.
7599 if (CI->capturesVariableArrayType()) {
7600 CurBasePointers.push_back(*CV);
7601 CurPointers.push_back(*CV);
7602 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7603 // Copy to the device as an argument. No need to retrieve it.
7604 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7605 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7606 } else {
7607 // If we have any information in the map clause, we use it, otherwise we
7608 // just do a default mapping.
7609 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7610 CurSizes, CurMapTypes);
7611 if (CurBasePointers.empty())
7612 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7613 CurPointers, CurSizes, CurMapTypes);
7614 }
7615 // We expect to have at least an element of information for this capture.
7616 assert(!CurBasePointers.empty() &&
7617 "Non-existing map pointer for capture!");
7618 assert(CurBasePointers.size() == CurPointers.size() &&
7619 CurBasePointers.size() == CurSizes.size() &&
7620 CurBasePointers.size() == CurMapTypes.size() &&
7621 "Inconsistent map information sizes!");
7622
7623 // We need to append the results of this capture to what we already have.
7624 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7625 Pointers.append(CurPointers.begin(), CurPointers.end());
7626 Sizes.append(CurSizes.begin(), CurSizes.end());
7627 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7628 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007629 // Map other list items in the map clause which are not captured variables
7630 // but "declare target link" global variables.
7631 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007632 for (const auto &L : C->component_lists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00007633 if (!L.first)
7634 continue;
7635 const auto *VD = dyn_cast<VarDecl>(L.first);
7636 if (!VD)
7637 continue;
7638 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7639 isDeclareTargetDeclaration(VD);
7640 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7641 continue;
7642 MEHandler.generateInfoForComponentList(
7643 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7644 Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7645 C->isImplicit());
7646 }
7647 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00007648
7649 TargetDataInfo Info;
7650 // Fill up the arrays and create the arguments.
7651 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7652 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7653 Info.PointersArray, Info.SizesArray,
7654 Info.MapTypesArray, Info);
7655 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7656 InputInfo.BasePointersArray =
7657 Address(Info.BasePointersArray, CGM.getPointerAlign());
7658 InputInfo.PointersArray =
7659 Address(Info.PointersArray, CGM.getPointerAlign());
7660 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7661 MapTypesArray = Info.MapTypesArray;
7662 if (RequiresOuterTask)
7663 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7664 else
7665 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7666 };
7667
7668 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7669 CodeGenFunction &CGF, PrePostActionTy &) {
7670 if (RequiresOuterTask) {
7671 CodeGenFunction::OMPTargetDataInfo InputInfo;
7672 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7673 } else {
7674 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7675 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007676 };
7677
7678 // If we have a target function ID it means that we need to support
7679 // offloading, otherwise, just execute on the host. We need to execute on host
7680 // regardless of the conditional in the if clause if, e.g., the user do not
7681 // specify target triples.
7682 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007683 if (IfCond) {
7684 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7685 } else {
7686 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007687 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007688 }
7689 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007690 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007691 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007692 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007693}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007694
7695void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7696 StringRef ParentName) {
7697 if (!S)
7698 return;
7699
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007700 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007701 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007702 isa<OMPExecutableDirective>(S) &&
7703 isOpenMPTargetExecutionDirective(
7704 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007705
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007706 if (RequiresDeviceCodegen) {
7707 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007708 unsigned DeviceID;
7709 unsigned FileID;
7710 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007711 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007712 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007713
7714 // Is this a target region that should not be emitted as an entry point? If
7715 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007716 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7717 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007718 return;
7719
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007720 switch (E.getDirectiveKind()) {
7721 case OMPD_target:
7722 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7723 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007724 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007725 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007726 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007727 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007728 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007729 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007730 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007731 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007732 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007733 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007734 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007735 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007736 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007737 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007738 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007739 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007740 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007741 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007742 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007743 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007744 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007745 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007746 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007747 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007748 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007749 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00007750 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007751 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00007752 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007753 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00007754 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7755 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007756 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00007757 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007758 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00007759 CodeGenFunction::
7760 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7761 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007762 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00007763 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007764 case OMPD_parallel:
7765 case OMPD_for:
7766 case OMPD_parallel_for:
7767 case OMPD_parallel_sections:
7768 case OMPD_for_simd:
7769 case OMPD_parallel_for_simd:
7770 case OMPD_cancel:
7771 case OMPD_cancellation_point:
7772 case OMPD_ordered:
7773 case OMPD_threadprivate:
7774 case OMPD_task:
7775 case OMPD_simd:
7776 case OMPD_sections:
7777 case OMPD_section:
7778 case OMPD_single:
7779 case OMPD_master:
7780 case OMPD_critical:
7781 case OMPD_taskyield:
7782 case OMPD_barrier:
7783 case OMPD_taskwait:
7784 case OMPD_taskgroup:
7785 case OMPD_atomic:
7786 case OMPD_flush:
7787 case OMPD_teams:
7788 case OMPD_target_data:
7789 case OMPD_target_exit_data:
7790 case OMPD_target_enter_data:
7791 case OMPD_distribute:
7792 case OMPD_distribute_simd:
7793 case OMPD_distribute_parallel_for:
7794 case OMPD_distribute_parallel_for_simd:
7795 case OMPD_teams_distribute:
7796 case OMPD_teams_distribute_simd:
7797 case OMPD_teams_distribute_parallel_for:
7798 case OMPD_teams_distribute_parallel_for_simd:
7799 case OMPD_target_update:
7800 case OMPD_declare_simd:
7801 case OMPD_declare_target:
7802 case OMPD_end_declare_target:
7803 case OMPD_declare_reduction:
7804 case OMPD_taskloop:
7805 case OMPD_taskloop_simd:
7806 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007807 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7808 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007809 return;
7810 }
7811
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007812 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007813 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007814 return;
7815
7816 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007817 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007818 return;
7819 }
7820
7821 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007822 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007823 S = L->getBody();
7824
7825 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007826 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007827 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007828}
7829
7830bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007831 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007832
7833 // If emitting code for the host, we do not process FD here. Instead we do
7834 // the normal code generation.
7835 if (!CGM.getLangOpts().OpenMPIsDevice)
7836 return false;
7837
7838 // Try to detect target regions in the function.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007839 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00007840
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007841 // Do not to emit function if it is not marked as declare target.
Alexey Bataevfb388282018-05-01 14:09:46 +00007842 return !isDeclareTargetDeclaration(FD) &&
7843 AlreadyEmittedTargetFunctions.count(FD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007844}
7845
7846bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7847 if (!CGM.getLangOpts().OpenMPIsDevice)
7848 return false;
7849
7850 // Check if there are Ctors/Dtors in this declaration and look for target
7851 // regions in it. We use the complete variant to produce the kernel name
7852 // mangling.
7853 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007854 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7855 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007856 StringRef ParentName =
7857 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7858 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7859 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007860 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007861 StringRef ParentName =
7862 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7863 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7864 }
7865 }
7866
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007867 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007868 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev03f270c2018-03-30 18:31:07 +00007869 isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
Alexey Bataev92327c52018-03-26 16:40:55 +00007870 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007871}
7872
Alexey Bataev03f270c2018-03-30 18:31:07 +00007873void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
7874 llvm::Constant *Addr) {
7875 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7876 isDeclareTargetDeclaration(VD)) {
7877 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
7878 StringRef VarName;
7879 CharUnits VarSize;
7880 llvm::GlobalValue::LinkageTypes Linkage;
7881 switch (*Res) {
7882 case OMPDeclareTargetDeclAttr::MT_To:
7883 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7884 VarName = CGM.getMangledName(VD);
7885 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
7886 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
7887 break;
7888 case OMPDeclareTargetDeclAttr::MT_Link:
7889 // Map type 'to' because we do not map the original variable but the
7890 // reference.
7891 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7892 if (!CGM.getLangOpts().OpenMPIsDevice) {
7893 Addr =
7894 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
7895 }
7896 VarName = Addr->getName();
7897 VarSize = CGM.getPointerSize();
7898 Linkage = llvm::GlobalValue::WeakAnyLinkage;
7899 break;
7900 }
7901 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
7902 VarName, Addr, VarSize, Flags, Linkage);
7903 }
7904}
7905
Samuel Antaoee8fb302016-01-06 13:42:12 +00007906bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007907 if (isa<FunctionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007908 return emitTargetFunctions(GD);
7909
7910 return emitTargetGlobalVariable(GD);
7911}
7912
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007913CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7914 CodeGenModule &CGM)
7915 : CGM(CGM) {
7916 if (CGM.getLangOpts().OpenMPIsDevice) {
7917 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7918 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7919 }
7920}
7921
7922CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7923 if (CGM.getLangOpts().OpenMPIsDevice)
7924 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7925}
7926
Alexey Bataev6d944102018-05-02 15:45:28 +00007927bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007928 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7929 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007930
Alexey Bataev6d944102018-05-02 15:45:28 +00007931 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007932 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00007933 // Do not to emit function if it is marked as declare target as it was already
7934 // emitted.
7935 if (isDeclareTargetDeclaration(D)) {
7936 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
7937 if (auto *F = dyn_cast_or_null<llvm::Function>(
Alexey Bataev6d944102018-05-02 15:45:28 +00007938 CGM.GetGlobalValue(CGM.getMangledName(GD))))
Alexey Bataev34f8a702018-03-28 14:28:54 +00007939 return !F->isDeclaration();
7940 return false;
7941 }
7942 return true;
7943 }
7944
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007945 return !AlreadyEmittedTargetFunctions.insert(FD).second;
7946}
7947
Samuel Antaoee8fb302016-01-06 13:42:12 +00007948llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7949 // If we have offloading in the current module, we need to emit the entries
7950 // now and register the offloading descriptor.
7951 createOffloadEntriesAndInfoMetadata();
7952
7953 // Create and register the offloading binary descriptors. This is the main
7954 // entity that captures all the information about offloading in the current
7955 // compilation unit.
7956 return createOffloadingBinaryDescriptorRegistration();
7957}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007958
7959void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7960 const OMPExecutableDirective &D,
7961 SourceLocation Loc,
7962 llvm::Value *OutlinedFn,
7963 ArrayRef<llvm::Value *> CapturedVars) {
7964 if (!CGF.HaveInsertPoint())
7965 return;
7966
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007967 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007968 CodeGenFunction::RunCleanupsScope Scope(CGF);
7969
7970 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7971 llvm::Value *Args[] = {
7972 RTLoc,
7973 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7974 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7975 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7976 RealArgs.append(std::begin(Args), std::end(Args));
7977 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7978
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007979 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007980 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7981}
7982
7983void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007984 const Expr *NumTeams,
7985 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007986 SourceLocation Loc) {
7987 if (!CGF.HaveInsertPoint())
7988 return;
7989
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007990 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007991
Carlo Bertollic6872252016-04-04 15:55:02 +00007992 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007993 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00007994 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7995 CGF.CGM.Int32Ty, /* isSigned = */ true)
7996 : CGF.Builder.getInt32(0);
7997
7998 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007999 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008000 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8001 CGF.CGM.Int32Ty, /* isSigned = */ true)
8002 : CGF.Builder.getInt32(0);
8003
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008004 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008005 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8006 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008007 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8008 PushNumTeamsArgs);
8009}
Samuel Antaodf158d52016-04-27 22:58:19 +00008010
Samuel Antaocc10b852016-07-28 14:23:26 +00008011void CGOpenMPRuntime::emitTargetDataCalls(
8012 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8013 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008014 if (!CGF.HaveInsertPoint())
8015 return;
8016
Samuel Antaocc10b852016-07-28 14:23:26 +00008017 // Action used to replace the default codegen action and turn privatization
8018 // off.
8019 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008020
8021 // Generate the code for the opening of the data environment. Capture all the
8022 // arguments of the runtime call by reference because they are used in the
8023 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008024 auto &&BeginThenGen = [this, &D, Device, &Info,
8025 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008026 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008027 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008028 MappableExprsHandler::MapValuesArrayTy Pointers;
8029 MappableExprsHandler::MapValuesArrayTy Sizes;
8030 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8031
8032 // Get map clause information.
8033 MappableExprsHandler MCHandler(D, CGF);
8034 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008035
8036 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008037 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008038
8039 llvm::Value *BasePointersArrayArg = nullptr;
8040 llvm::Value *PointersArrayArg = nullptr;
8041 llvm::Value *SizesArrayArg = nullptr;
8042 llvm::Value *MapTypesArrayArg = nullptr;
8043 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008044 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008045
8046 // Emit device ID if any.
8047 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008048 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008049 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008050 CGF.Int64Ty, /*isSigned=*/true);
8051 } else {
8052 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8053 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008054
8055 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008056 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008057
8058 llvm::Value *OffloadingArgs[] = {
8059 DeviceID, PointerNum, BasePointersArrayArg,
8060 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008061 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008062 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008063
8064 // If device pointer privatization is required, emit the body of the region
8065 // here. It will have to be duplicated: with and without privatization.
8066 if (!Info.CaptureDeviceAddrMap.empty())
8067 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008068 };
8069
8070 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008071 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8072 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008073 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008074
8075 llvm::Value *BasePointersArrayArg = nullptr;
8076 llvm::Value *PointersArrayArg = nullptr;
8077 llvm::Value *SizesArrayArg = nullptr;
8078 llvm::Value *MapTypesArrayArg = nullptr;
8079 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008080 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008081
8082 // Emit device ID if any.
8083 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008084 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008085 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008086 CGF.Int64Ty, /*isSigned=*/true);
8087 } else {
8088 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8089 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008090
8091 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008092 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008093
8094 llvm::Value *OffloadingArgs[] = {
8095 DeviceID, PointerNum, BasePointersArrayArg,
8096 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008097 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008098 OffloadingArgs);
8099 };
8100
Samuel Antaocc10b852016-07-28 14:23:26 +00008101 // If we need device pointer privatization, we need to emit the body of the
8102 // region with no privatization in the 'else' branch of the conditional.
8103 // Otherwise, we don't have to do anything.
8104 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8105 PrePostActionTy &) {
8106 if (!Info.CaptureDeviceAddrMap.empty()) {
8107 CodeGen.setAction(NoPrivAction);
8108 CodeGen(CGF);
8109 }
8110 };
8111
8112 // We don't have to do anything to close the region if the if clause evaluates
8113 // to false.
8114 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008115
8116 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008117 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008118 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008119 RegionCodeGenTy RCG(BeginThenGen);
8120 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008121 }
8122
Samuel Antaocc10b852016-07-28 14:23:26 +00008123 // If we don't require privatization of device pointers, we emit the body in
8124 // between the runtime calls. This avoids duplicating the body code.
8125 if (Info.CaptureDeviceAddrMap.empty()) {
8126 CodeGen.setAction(NoPrivAction);
8127 CodeGen(CGF);
8128 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008129
8130 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008131 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008132 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008133 RegionCodeGenTy RCG(EndThenGen);
8134 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008135 }
8136}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008137
Samuel Antao8d2d7302016-05-26 18:30:22 +00008138void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008139 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8140 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008141 if (!CGF.HaveInsertPoint())
8142 return;
8143
Samuel Antao8dd66282016-04-27 23:14:30 +00008144 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008145 isa<OMPTargetExitDataDirective>(D) ||
8146 isa<OMPTargetUpdateDirective>(D)) &&
8147 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008148
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008149 CodeGenFunction::OMPTargetDataInfo InputInfo;
8150 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008151 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008152 auto &&ThenGen = [this, &D, Device, &InputInfo,
8153 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008154 // Emit device ID if any.
8155 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008156 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008157 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008158 CGF.Int64Ty, /*isSigned=*/true);
8159 } else {
8160 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8161 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008162
8163 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008164 llvm::Constant *PointerNum =
8165 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008166
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008167 llvm::Value *OffloadingArgs[] = {DeviceID,
8168 PointerNum,
8169 InputInfo.BasePointersArray.getPointer(),
8170 InputInfo.PointersArray.getPointer(),
8171 InputInfo.SizesArray.getPointer(),
8172 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008173
Samuel Antao8d2d7302016-05-26 18:30:22 +00008174 // Select the right runtime function call for each expected standalone
8175 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008176 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008177 OpenMPRTLFunction RTLFn;
8178 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008179 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008180 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8181 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008182 break;
8183 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008184 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8185 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008186 break;
8187 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008188 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8189 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008190 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008191 case OMPD_parallel:
8192 case OMPD_for:
8193 case OMPD_parallel_for:
8194 case OMPD_parallel_sections:
8195 case OMPD_for_simd:
8196 case OMPD_parallel_for_simd:
8197 case OMPD_cancel:
8198 case OMPD_cancellation_point:
8199 case OMPD_ordered:
8200 case OMPD_threadprivate:
8201 case OMPD_task:
8202 case OMPD_simd:
8203 case OMPD_sections:
8204 case OMPD_section:
8205 case OMPD_single:
8206 case OMPD_master:
8207 case OMPD_critical:
8208 case OMPD_taskyield:
8209 case OMPD_barrier:
8210 case OMPD_taskwait:
8211 case OMPD_taskgroup:
8212 case OMPD_atomic:
8213 case OMPD_flush:
8214 case OMPD_teams:
8215 case OMPD_target_data:
8216 case OMPD_distribute:
8217 case OMPD_distribute_simd:
8218 case OMPD_distribute_parallel_for:
8219 case OMPD_distribute_parallel_for_simd:
8220 case OMPD_teams_distribute:
8221 case OMPD_teams_distribute_simd:
8222 case OMPD_teams_distribute_parallel_for:
8223 case OMPD_teams_distribute_parallel_for_simd:
8224 case OMPD_declare_simd:
8225 case OMPD_declare_target:
8226 case OMPD_end_declare_target:
8227 case OMPD_declare_reduction:
8228 case OMPD_taskloop:
8229 case OMPD_taskloop_simd:
8230 case OMPD_target:
8231 case OMPD_target_simd:
8232 case OMPD_target_teams_distribute:
8233 case OMPD_target_teams_distribute_simd:
8234 case OMPD_target_teams_distribute_parallel_for:
8235 case OMPD_target_teams_distribute_parallel_for_simd:
8236 case OMPD_target_teams:
8237 case OMPD_target_parallel:
8238 case OMPD_target_parallel_for:
8239 case OMPD_target_parallel_for_simd:
8240 case OMPD_unknown:
8241 llvm_unreachable("Unexpected standalone target data directive.");
8242 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008243 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008244 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008245 };
8246
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008247 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8248 CodeGenFunction &CGF, PrePostActionTy &) {
8249 // Fill up the arrays with all the mapped variables.
8250 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8251 MappableExprsHandler::MapValuesArrayTy Pointers;
8252 MappableExprsHandler::MapValuesArrayTy Sizes;
8253 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008254
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008255 // Get map clause information.
8256 MappableExprsHandler MEHandler(D, CGF);
8257 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8258
8259 TargetDataInfo Info;
8260 // Fill up the arrays and create the arguments.
8261 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8262 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8263 Info.PointersArray, Info.SizesArray,
8264 Info.MapTypesArray, Info);
8265 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8266 InputInfo.BasePointersArray =
8267 Address(Info.BasePointersArray, CGM.getPointerAlign());
8268 InputInfo.PointersArray =
8269 Address(Info.PointersArray, CGM.getPointerAlign());
8270 InputInfo.SizesArray =
8271 Address(Info.SizesArray, CGM.getPointerAlign());
8272 MapTypesArray = Info.MapTypesArray;
8273 if (D.hasClausesOfKind<OMPDependClause>())
8274 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8275 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008276 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008277 };
8278
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008279 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008280 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8281 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008282 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008283 RegionCodeGenTy ThenRCG(TargetThenGen);
8284 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008285 }
8286}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008287
8288namespace {
8289 /// Kind of parameter in a function with 'declare simd' directive.
8290 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8291 /// Attribute set of the parameter.
8292 struct ParamAttrTy {
8293 ParamKindTy Kind = Vector;
8294 llvm::APSInt StrideOrArg;
8295 llvm::APSInt Alignment;
8296 };
8297} // namespace
8298
8299static unsigned evaluateCDTSize(const FunctionDecl *FD,
8300 ArrayRef<ParamAttrTy> ParamAttrs) {
8301 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8302 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8303 // of that clause. The VLEN value must be power of 2.
8304 // In other case the notion of the function`s "characteristic data type" (CDT)
8305 // is used to compute the vector length.
8306 // CDT is defined in the following order:
8307 // a) For non-void function, the CDT is the return type.
8308 // b) If the function has any non-uniform, non-linear parameters, then the
8309 // CDT is the type of the first such parameter.
8310 // c) If the CDT determined by a) or b) above is struct, union, or class
8311 // type which is pass-by-value (except for the type that maps to the
8312 // built-in complex data type), the characteristic data type is int.
8313 // d) If none of the above three cases is applicable, the CDT is int.
8314 // The VLEN is then determined based on the CDT and the size of vector
8315 // register of that ISA for which current vector version is generated. The
8316 // VLEN is computed using the formula below:
8317 // VLEN = sizeof(vector_register) / sizeof(CDT),
8318 // where vector register size specified in section 3.2.1 Registers and the
8319 // Stack Frame of original AMD64 ABI document.
8320 QualType RetType = FD->getReturnType();
8321 if (RetType.isNull())
8322 return 0;
8323 ASTContext &C = FD->getASTContext();
8324 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008325 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008326 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008327 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008328 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008329 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008330 if (ParamAttrs[Offset].Kind == Vector)
8331 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8332 ++Offset;
8333 }
8334 if (CDT.isNull()) {
8335 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8336 if (ParamAttrs[I + Offset].Kind == Vector) {
8337 CDT = FD->getParamDecl(I)->getType();
8338 break;
8339 }
8340 }
8341 }
8342 }
8343 if (CDT.isNull())
8344 CDT = C.IntTy;
8345 CDT = CDT->getCanonicalTypeUnqualified();
8346 if (CDT->isRecordType() || CDT->isUnionType())
8347 CDT = C.IntTy;
8348 return C.getTypeSize(CDT);
8349}
8350
8351static void
8352emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008353 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008354 ArrayRef<ParamAttrTy> ParamAttrs,
8355 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8356 struct ISADataTy {
8357 char ISA;
8358 unsigned VecRegSize;
8359 };
8360 ISADataTy ISAData[] = {
8361 {
8362 'b', 128
8363 }, // SSE
8364 {
8365 'c', 256
8366 }, // AVX
8367 {
8368 'd', 256
8369 }, // AVX2
8370 {
8371 'e', 512
8372 }, // AVX512
8373 };
8374 llvm::SmallVector<char, 2> Masked;
8375 switch (State) {
8376 case OMPDeclareSimdDeclAttr::BS_Undefined:
8377 Masked.push_back('N');
8378 Masked.push_back('M');
8379 break;
8380 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8381 Masked.push_back('N');
8382 break;
8383 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8384 Masked.push_back('M');
8385 break;
8386 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008387 for (char Mask : Masked) {
8388 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008389 SmallString<256> Buffer;
8390 llvm::raw_svector_ostream Out(Buffer);
8391 Out << "_ZGV" << Data.ISA << Mask;
8392 if (!VLENVal) {
8393 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8394 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008395 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008396 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008397 }
8398 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008399 switch (ParamAttr.Kind){
8400 case LinearWithVarStride:
8401 Out << 's' << ParamAttr.StrideOrArg;
8402 break;
8403 case Linear:
8404 Out << 'l';
8405 if (!!ParamAttr.StrideOrArg)
8406 Out << ParamAttr.StrideOrArg;
8407 break;
8408 case Uniform:
8409 Out << 'u';
8410 break;
8411 case Vector:
8412 Out << 'v';
8413 break;
8414 }
8415 if (!!ParamAttr.Alignment)
8416 Out << 'a' << ParamAttr.Alignment;
8417 }
8418 Out << '_' << Fn->getName();
8419 Fn->addFnAttr(Out.str());
8420 }
8421 }
8422}
8423
8424void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8425 llvm::Function *Fn) {
8426 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008427 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008428 // Map params to their positions in function decl.
8429 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8430 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008431 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008432 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008433 for (const ParmVarDecl *P : FD->parameters()) {
8434 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008435 ++ParamPos;
8436 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008437 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008438 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008439 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8440 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008441 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008442 E = E->IgnoreParenImpCasts();
8443 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008444 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008445 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008446 } else {
8447 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8448 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008449 Pos = ParamPositions[PVD];
8450 }
8451 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008452 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008453 // Get alignment info.
8454 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008455 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008456 E = E->IgnoreParenImpCasts();
8457 unsigned Pos;
8458 QualType ParmTy;
8459 if (isa<CXXThisExpr>(E)) {
8460 Pos = ParamPositions[FD];
8461 ParmTy = E->getType();
8462 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008463 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8464 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008465 Pos = ParamPositions[PVD];
8466 ParmTy = PVD->getType();
8467 }
8468 ParamAttrs[Pos].Alignment =
8469 (*NI)
8470 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008471 : llvm::APSInt::getUnsigned(
8472 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8473 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008474 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008475 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008476 // Mark linear parameters.
8477 auto SI = Attr->steps_begin();
8478 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008479 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008480 E = E->IgnoreParenImpCasts();
8481 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008482 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008483 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008484 } else {
8485 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8486 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008487 Pos = ParamPositions[PVD];
8488 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008489 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008490 ParamAttr.Kind = Linear;
8491 if (*SI) {
8492 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8493 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008494 if (const auto *DRE =
8495 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8496 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008497 ParamAttr.Kind = LinearWithVarStride;
8498 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8499 ParamPositions[StridePVD->getCanonicalDecl()]);
8500 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008501 }
8502 }
8503 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008504 ++SI;
8505 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008506 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008507 llvm::APSInt VLENVal;
8508 if (const Expr *VLEN = Attr->getSimdlen())
8509 VLENVal = VLEN->EvaluateKnownConstInt(C);
8510 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8511 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8512 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8513 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008514 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008515 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008516 }
8517}
Alexey Bataev8b427062016-05-25 12:36:08 +00008518
8519namespace {
8520/// Cleanup action for doacross support.
8521class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8522public:
8523 static const int DoacrossFinArgs = 2;
8524
8525private:
8526 llvm::Value *RTLFn;
8527 llvm::Value *Args[DoacrossFinArgs];
8528
8529public:
8530 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8531 : RTLFn(RTLFn) {
8532 assert(CallArgs.size() == DoacrossFinArgs);
8533 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8534 }
8535 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8536 if (!CGF.HaveInsertPoint())
8537 return;
8538 CGF.EmitRuntimeCall(RTLFn, Args);
8539 }
8540};
8541} // namespace
8542
8543void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8544 const OMPLoopDirective &D) {
8545 if (!CGF.HaveInsertPoint())
8546 return;
8547
8548 ASTContext &C = CGM.getContext();
8549 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8550 RecordDecl *RD;
8551 if (KmpDimTy.isNull()) {
8552 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8553 // kmp_int64 lo; // lower
8554 // kmp_int64 up; // upper
8555 // kmp_int64 st; // stride
8556 // };
8557 RD = C.buildImplicitRecord("kmp_dim");
8558 RD->startDefinition();
8559 addFieldToRecordDecl(C, RD, Int64Ty);
8560 addFieldToRecordDecl(C, RD, Int64Ty);
8561 addFieldToRecordDecl(C, RD, Int64Ty);
8562 RD->completeDefinition();
8563 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008564 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008565 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008566 }
Alexey Bataev8b427062016-05-25 12:36:08 +00008567
8568 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8569 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8570 enum { LowerFD = 0, UpperFD, StrideFD };
8571 // Fill dims with data.
8572 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8573 // dims.upper = num_iterations;
8574 LValue UpperLVal =
8575 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8576 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8577 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8578 Int64Ty, D.getNumIterations()->getExprLoc());
8579 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8580 // dims.stride = 1;
8581 LValue StrideLVal =
8582 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8583 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8584 StrideLVal);
8585
8586 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8587 // kmp_int32 num_dims, struct kmp_dim * dims);
8588 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8589 getThreadID(CGF, D.getLocStart()),
8590 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8591 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8592 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8593
8594 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8595 CGF.EmitRuntimeCall(RTLFn, Args);
8596 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8597 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8598 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8599 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8600 llvm::makeArrayRef(FiniArgs));
8601}
8602
8603void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8604 const OMPDependClause *C) {
8605 QualType Int64Ty =
8606 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8607 const Expr *CounterVal = C->getCounterValue();
8608 assert(CounterVal);
8609 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8610 CounterVal->getType(), Int64Ty,
8611 CounterVal->getExprLoc());
8612 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8613 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8614 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8615 getThreadID(CGF, C->getLocStart()),
8616 CntAddr.getPointer()};
8617 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008618 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008619 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008620 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008621 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8622 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8623 }
8624 CGF.EmitRuntimeCall(RTLFn, Args);
8625}
8626
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008627void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8628 llvm::Value *Callee,
8629 ArrayRef<llvm::Value *> Args) const {
8630 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008631 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8632
8633 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008634 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008635 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008636 return;
8637 }
8638 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008639 CGF.EmitRuntimeCall(Callee, Args);
8640}
8641
8642void CGOpenMPRuntime::emitOutlinedFunctionCall(
8643 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8644 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008645 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008646}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008647
8648Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8649 const VarDecl *NativeParam,
8650 const VarDecl *TargetParam) const {
8651 return CGF.GetAddrOfLocalVar(NativeParam);
8652}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008653
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008654Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8655 const VarDecl *VD) {
8656 return Address::invalid();
8657}
8658
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008659llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8660 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8661 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8662 llvm_unreachable("Not supported in SIMD-only mode");
8663}
8664
8665llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8666 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8667 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8668 llvm_unreachable("Not supported in SIMD-only mode");
8669}
8670
8671llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8672 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8673 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8674 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8675 bool Tied, unsigned &NumberOfParts) {
8676 llvm_unreachable("Not supported in SIMD-only mode");
8677}
8678
8679void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8680 SourceLocation Loc,
8681 llvm::Value *OutlinedFn,
8682 ArrayRef<llvm::Value *> CapturedVars,
8683 const Expr *IfCond) {
8684 llvm_unreachable("Not supported in SIMD-only mode");
8685}
8686
8687void CGOpenMPSIMDRuntime::emitCriticalRegion(
8688 CodeGenFunction &CGF, StringRef CriticalName,
8689 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8690 const Expr *Hint) {
8691 llvm_unreachable("Not supported in SIMD-only mode");
8692}
8693
8694void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8695 const RegionCodeGenTy &MasterOpGen,
8696 SourceLocation Loc) {
8697 llvm_unreachable("Not supported in SIMD-only mode");
8698}
8699
8700void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8701 SourceLocation Loc) {
8702 llvm_unreachable("Not supported in SIMD-only mode");
8703}
8704
8705void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8706 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8707 SourceLocation Loc) {
8708 llvm_unreachable("Not supported in SIMD-only mode");
8709}
8710
8711void CGOpenMPSIMDRuntime::emitSingleRegion(
8712 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8713 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8714 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8715 ArrayRef<const Expr *> AssignmentOps) {
8716 llvm_unreachable("Not supported in SIMD-only mode");
8717}
8718
8719void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8720 const RegionCodeGenTy &OrderedOpGen,
8721 SourceLocation Loc,
8722 bool IsThreads) {
8723 llvm_unreachable("Not supported in SIMD-only mode");
8724}
8725
8726void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8727 SourceLocation Loc,
8728 OpenMPDirectiveKind Kind,
8729 bool EmitChecks,
8730 bool ForceSimpleCall) {
8731 llvm_unreachable("Not supported in SIMD-only mode");
8732}
8733
8734void CGOpenMPSIMDRuntime::emitForDispatchInit(
8735 CodeGenFunction &CGF, SourceLocation Loc,
8736 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8737 bool Ordered, const DispatchRTInput &DispatchValues) {
8738 llvm_unreachable("Not supported in SIMD-only mode");
8739}
8740
8741void CGOpenMPSIMDRuntime::emitForStaticInit(
8742 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8743 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8744 llvm_unreachable("Not supported in SIMD-only mode");
8745}
8746
8747void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8748 CodeGenFunction &CGF, SourceLocation Loc,
8749 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8750 llvm_unreachable("Not supported in SIMD-only mode");
8751}
8752
8753void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8754 SourceLocation Loc,
8755 unsigned IVSize,
8756 bool IVSigned) {
8757 llvm_unreachable("Not supported in SIMD-only mode");
8758}
8759
8760void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8761 SourceLocation Loc,
8762 OpenMPDirectiveKind DKind) {
8763 llvm_unreachable("Not supported in SIMD-only mode");
8764}
8765
8766llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8767 SourceLocation Loc,
8768 unsigned IVSize, bool IVSigned,
8769 Address IL, Address LB,
8770 Address UB, Address ST) {
8771 llvm_unreachable("Not supported in SIMD-only mode");
8772}
8773
8774void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8775 llvm::Value *NumThreads,
8776 SourceLocation Loc) {
8777 llvm_unreachable("Not supported in SIMD-only mode");
8778}
8779
8780void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8781 OpenMPProcBindClauseKind ProcBind,
8782 SourceLocation Loc) {
8783 llvm_unreachable("Not supported in SIMD-only mode");
8784}
8785
8786Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8787 const VarDecl *VD,
8788 Address VDAddr,
8789 SourceLocation Loc) {
8790 llvm_unreachable("Not supported in SIMD-only mode");
8791}
8792
8793llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8794 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8795 CodeGenFunction *CGF) {
8796 llvm_unreachable("Not supported in SIMD-only mode");
8797}
8798
8799Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8800 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8801 llvm_unreachable("Not supported in SIMD-only mode");
8802}
8803
8804void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8805 ArrayRef<const Expr *> Vars,
8806 SourceLocation Loc) {
8807 llvm_unreachable("Not supported in SIMD-only mode");
8808}
8809
8810void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8811 const OMPExecutableDirective &D,
8812 llvm::Value *TaskFunction,
8813 QualType SharedsTy, Address Shareds,
8814 const Expr *IfCond,
8815 const OMPTaskDataTy &Data) {
8816 llvm_unreachable("Not supported in SIMD-only mode");
8817}
8818
8819void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8820 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8821 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8822 const Expr *IfCond, const OMPTaskDataTy &Data) {
8823 llvm_unreachable("Not supported in SIMD-only mode");
8824}
8825
8826void CGOpenMPSIMDRuntime::emitReduction(
8827 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8828 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8829 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8830 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8831 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8832 ReductionOps, Options);
8833}
8834
8835llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8836 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8837 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8838 llvm_unreachable("Not supported in SIMD-only mode");
8839}
8840
8841void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8842 SourceLocation Loc,
8843 ReductionCodeGen &RCG,
8844 unsigned N) {
8845 llvm_unreachable("Not supported in SIMD-only mode");
8846}
8847
8848Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8849 SourceLocation Loc,
8850 llvm::Value *ReductionsPtr,
8851 LValue SharedLVal) {
8852 llvm_unreachable("Not supported in SIMD-only mode");
8853}
8854
8855void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8856 SourceLocation Loc) {
8857 llvm_unreachable("Not supported in SIMD-only mode");
8858}
8859
8860void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8861 CodeGenFunction &CGF, SourceLocation Loc,
8862 OpenMPDirectiveKind CancelRegion) {
8863 llvm_unreachable("Not supported in SIMD-only mode");
8864}
8865
8866void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8867 SourceLocation Loc, const Expr *IfCond,
8868 OpenMPDirectiveKind CancelRegion) {
8869 llvm_unreachable("Not supported in SIMD-only mode");
8870}
8871
8872void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8873 const OMPExecutableDirective &D, StringRef ParentName,
8874 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8875 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8876 llvm_unreachable("Not supported in SIMD-only mode");
8877}
8878
8879void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8880 const OMPExecutableDirective &D,
8881 llvm::Value *OutlinedFn,
8882 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008883 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008884 llvm_unreachable("Not supported in SIMD-only mode");
8885}
8886
8887bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8888 llvm_unreachable("Not supported in SIMD-only mode");
8889}
8890
8891bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8892 llvm_unreachable("Not supported in SIMD-only mode");
8893}
8894
8895bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8896 return false;
8897}
8898
8899llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8900 return nullptr;
8901}
8902
8903void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8904 const OMPExecutableDirective &D,
8905 SourceLocation Loc,
8906 llvm::Value *OutlinedFn,
8907 ArrayRef<llvm::Value *> CapturedVars) {
8908 llvm_unreachable("Not supported in SIMD-only mode");
8909}
8910
8911void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8912 const Expr *NumTeams,
8913 const Expr *ThreadLimit,
8914 SourceLocation Loc) {
8915 llvm_unreachable("Not supported in SIMD-only mode");
8916}
8917
8918void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8919 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8920 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8921 llvm_unreachable("Not supported in SIMD-only mode");
8922}
8923
8924void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8925 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8926 const Expr *Device) {
8927 llvm_unreachable("Not supported in SIMD-only mode");
8928}
8929
8930void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8931 const OMPLoopDirective &D) {
8932 llvm_unreachable("Not supported in SIMD-only mode");
8933}
8934
8935void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8936 const OMPDependClause *C) {
8937 llvm_unreachable("Not supported in SIMD-only mode");
8938}
8939
8940const VarDecl *
8941CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8942 const VarDecl *NativeParam) const {
8943 llvm_unreachable("Not supported in SIMD-only mode");
8944}
8945
8946Address
8947CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8948 const VarDecl *NativeParam,
8949 const VarDecl *TargetParam) const {
8950 llvm_unreachable("Not supported in SIMD-only mode");
8951}
8952